如果我从input.txt中提取一个字符串,如何用逗号3次将其输出到output.txt中,并显示出其中字符数,使用c语言,程序是dev-C++
时间: 2024-03-05 20:54:01 浏览: 19
以下是使用C语言实现的代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
FILE *input_file, *output_file;
char string[100];
input_file = fopen("input.txt", "r");
fgets(string, 100, input_file); // 从input.txt中读取字符串
fclose(input_file);
strcat(string, ",,,"); // 在字符串后面添加3个逗号
output_file = fopen("output.txt", "w");
fputs(string, output_file); // 将新字符串写入output.txt
fclose(output_file);
printf("字符串长度:%d\n", strlen(string)); // 输出字符串长度
return 0;
}
```
这段代码首先定义了两个指向文件的指针变量`input_file`和`output_file`,以及一个字符数组`string`用于存储从input.txt中读取的字符串。然后使用`fopen()`函数打开input.txt文件,并使用`fgets()`函数将第一行字符串读取到`string`数组中,最后关闭文件。
接着在字符串后面使用`strcat()`函数添加3个逗号。然后使用`fopen()`函数打开output.txt文件,并使用`fputs()`函数将新字符串写入文件中,最后关闭文件。
最后使用`strlen()`函数计算新字符串的长度,并使用`printf()`函数输出字符串长度。
注意,使用`fgets()`函数读取字符串时,需要指定读取的最大字符数,以避免内存溢出。在本例中,我指定了100作为最大字符数。如果读取的字符串超过了100个字符,就需要增加数组的大小。