使用c++语言提取一个文本文件中的数值,将它们写入另一个新文件,由空白或其他字符分开的数字被认为是不同的数值
时间: 2023-05-28 13:06:32 浏览: 105
以下是一个简单的示例代码,可以从一个文本文件中提取数字,并将它们写入另一个文件中:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
FILE *input_file, *output_file;
char input_filename[100], output_filename[100], ch;
double num;
int flag = 0;
printf("Enter the input filename: ");
scanf("%s", input_filename);
input_file = fopen(input_filename, "r");
if (input_file == NULL) {
printf("Error opening input file.\n");
exit(1);
}
printf("Enter the output filename: ");
scanf("%s", output_filename);
output_file = fopen(output_filename, "w");
if (output_file == NULL) {
printf("Error opening output file.\n");
exit(1);
}
while ((ch = fgetc(input_file)) != EOF) {
if (isdigit(ch) || ch == '.' || ch == '-') {
flag = 1;
ungetc(ch, input_file);
fscanf(input_file, "%lf", &num);
fprintf(output_file, "%.2lf ", num);
} else if (flag == 1) {
flag = 0;
fprintf(output_file, "\n");
}
}
fclose(input_file);
fclose(output_file);
return 0;
}
```
以上代码中,首先要求用户输入要读取的文件名和要写入的文件名。然后打开这两个文件,并逐个读取源文件中的字符。如果当前字符是数字、小数点或负号,则将其作为数值读取,并将其写入目标文件中。如果当前字符不是数字,则检查前面是否已经读取了一个数值,如果是,则在目标文件中写入一个换行符。最后关闭文件并退出程序。
需要注意的是,在读取数字时,我们使用了 fscanf 函数而不是 scanf 函数。因为 scanf 函数会在读取数字后停止,而 fscanf 函数会继续读取下一个字符,以便下一次循环可以正确地处理它。另外,我们还使用了 ungetc 函数,以便将最后一个读取的字符放回输入流中,以便 fscanf 函数可以正确地读取数字。