
设要写入的数字是int型,则用控制字符串%d和%s来完成,举例代码行如下:
fprintf(fp,"%d %s\n",12345,"abcdefg")
其中:fp是成功写打开文件的指针。此代码行先向文件写入整型数字12345,再加一个空格,接着写入字符串abcdefg,然后写入'\n'。
#include "stdio.h"
#include "string.h"
void main()
{
char a[6]="china"
char temp[1024]
int n=0//记录有多少个china
FILE *outFile=fopen("c:\b.txt","r+")
FILE *inFile=fopen("c:\a.txt","r+")
while(fgets(temp,500,inFile)!=NULL)
{
int k=0
for(int i=0i<strlen(temp)i++)
{
if(temp[i]==a[k] &&k<strlen(a))
{
k++
}
else
{
if(k==strlen(a))
{
n++
fprintf(outFile,"%s
",a)
}
k=0
}
}
}
}
在C盘要有这两个文件。。。
a文件中可能有多个china ,指定加到第几行自己看情况 在设置一个int变量记录就行了
以下是一个简单的C语言程序,可以实现将键盘输入的字符串写入文件中,并统计其中字母、数字、空格和其他字符出现的次数,并将字母和数字存放到另一个文件中:```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[1000], ch
int i = 0, letter_count = 0, digit_count = 0, space_count = 0, other_count = 0
// 从用户输入中读取字符串
printf("Enter a string: ")
fgets(str, sizeof(str), stdin)
// 将字符串写入文件并统计字符出现次数
FILE *fp = fopen("input.txt", "w")
if (fp == NULL) {
perror("fopen")
return 1
}
while ((ch = str[i++]) != '\0') {
fputc(ch, fp)
if (isalpha(ch)) {
letter_count++
} else if (isdigit(ch)) {
digit_count++
} else if (isspace(ch)) {
space_count++
} else {
other_count++
}
}
fclose(fp)
// 统计字母和数字出现次数并将其存入文件
fp = fopen("output.txt", "w")
if (fp == NULL) {
perror("fopen")
return 1
}
fprintf(fp, "Letters: %d\n", letter_count)
fprintf(fp, "Digits: %d\n", digit_count)
fclose(fp)
// 输出字符出现次数的统计结果
printf("Letter count: %d\n", letter_count)
printf("Digit count: %d\n", digit_count)
printf("Space count: %d\n", space_count)
printf("Other count: %d\n", other_count)
return 0
}
```
在上述代码中,我们使用 `fgets()` 函数从用户输入中读取字符串,并将其写入名为 `input.txt` 的文本文件中。在此过程中,我们使用了 `isalpha()` 和 `isdigit()` 等函数判断字符类型,并统计其中字母、数字、空格和其他字符的出现次数。
然后,我们使用 `fprintf()` 函数将字母和数字的出现次数分别存入名为 `output.txt` 的文件中。
最后,输出字符出现次数的统计结果。
需要注意的是,在实际应用中还需要考虑更多的边界情况和错误处理。例如,可能出现无法打开或关闭文件、读写文件出错等问题。此外,如果输入的字符串超出预设数组大小,可能会引起缓冲区溢出等问题。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)