我什至不确定是否从这里开始,但本质上我不想使用用户输入来运行我的程序,而是想使用 .txt 来接收和存储我的输入。
例如,.txt 文件显示如下:
1 2 3
5 6
8 9 10
如何打开此 .txt 文件并将每个单独的数字存储为程序中的变量?
最佳答案
所有这些都假设您提供的示例输入。调整到不同的输入排列留给读者作为练习......
几乎是最简单的程序(假设您运行:./myprogram < myfile.txt)
#include <stdio.h>
int main ( void ) {
int a, b, c, d, e, f, g, h; /* terrible variable names */
scanf("%d %d %d", &a, &b, &c);
scanf("%d %d", &d, &e);
scanf("%d %d %d", &f, &g, &h);
return 0;
}
下一步,从命名文件中读取:
int main ( void ) {
FILE * fp;
int a, b, c, d, e, f, g, h; /* terrible variable names */
fp = fopen("myfile.txt", "r");
if (fp == NULL) {
perror("open failed");
return 1;
}
fscanf(fp, "%d %d %d", &a, &b, &c);
fscanf(fp, "%d %d", &d, &e);
fscanf(fp, "%d %d %d", &f, &g, &h);
fclose(fp);
return 0;
}
注意这些变化。改进这一点的下一步是从命令行获取文件名。
int main ( int argc, char * argv[] ) {
FILE * fp;
int a, b, c, d, e, f, g, h; /* terrible variable names */
char * filename;
if (argc > 1) filename = argv[1];
else {
fprintf(stderr, "please supply an input filename on the command line\n");
return 2;
}
fp = fopen(filename, "r");
/* and then continues as in the version above... */
}
再次注意更改。
关于c - 在 C 程序中使用 .txt 接收输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25813042/