如何从C中的.txt文件读取并打印前5个整数?
问题描述:
我试图从C中的.txt文件中读取并打印前五个整数。 我有几个文件,其中包含使用命令行参数可以读取的各种整数列表。如何从C中的.txt文件读取并打印前5个整数?
例如,如果我输入
./firstFive 50to100.txt
[文件50to100.txt包含一个新行分开的整数50-100]
所以该程序应该打印 -
50
51
52
53
54
由于有几个不同的文件需要读取(全部包含整数),我使用“fp”作为捕获所有文件以打开argv [1]指定的文件。
这里是我迄今为止 -
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fp;
int num;
int i;
if (argc < 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return 1;
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "%s: unable to open file %s,\n", argv[0], argv[1]);
return 1;
}
while (fscanf(fp, "%d", &num) == 1) {
for(i=0; i<5; i++) {
printf("%c/n", num[i]);
}
}
fclose(fp);
return 0;
}
目前,它甚至不会编译。任何想法出了什么问题?由于正试图读取化妆的整数,这是不是你的意图(我相信)和编译器不会像字节
int num;
...
for(i=0; i<5; i++) {
printf("%c/n", num[i]);
}
:
答
编译器不会喜欢这个您试图将int
视为一个数组。
这应该工作:
unsigned count = 0;
while (count < 5 && fscanf(fp, "%d", &num) == 1) {
printf("%d\n", num);
count++;
}
它基本上增加为5限制循环。
答
num
是一个简单的字符,而不是一个数组。所以你不能使用num[i]
。由于您只需要文件的前5行而不是整个文件,您应该在读取级别上具有for循环。 while循环将读取整个文件。
printf语句应该是%d,因为它是一个整数。
像这样的事情
for(i=0; i<5; i++) {
if (fscanf(fp, "%d", &num) == 1) {
printf("%d\n", num);
}
}
答
可能有不同的方式例如像
- 使用的fscanf或
- 使用读/写函数,然后转换ASCII到整数 等
考虑到已存储在这个顺序串在你.TXT文件。
...
40
50
60
70
....
然后做出以下更改。
int main(int argc, char *argv[]) {
FILE *fp;
int num;
int i = 5;
if (argc < 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return 1;
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "%s: unable to open file %s,\n", argv[0], argv[1]);
return 1;
}
while (fscanf(fp, "%d", &num) ==1 && i-- >= 1) {
printf(" %d \n", num);
}
fclose(fp);
return 0;
}
而且见下面链接,scanf函数
http://www.tutorialspoint.com/c_standard_library/c_function_fscanf.htm
答
你可能在寻找这样的事情:
//...
int num; //don't need an array for reading a single number
for (int i = 0; i < 5; i++){ //if you know you need just five numbers set it in the counter
if(fscanf(fp, "%d", &num) == 1)//read about fscanf() and EOF check
printf("%d\n", num); //read about printf()
}
fclose(fp);
// ...
'目前,它甚至不会compile' ..为什么?小心分享? –
如果一个程序没有编译,你的编译器会给你一个*编译器的错误信息*,其中包含有关“发生了什么问题”的信息。您可以*阅读*并* *对错误消息采取行动以改善您的代码。 –
不会导致代码无法编译,但这个'/ n'最喜欢的应该是'\ n'。 – alk