我正在学习 C 并通过编写一个从文本文件读取整数并将它们存储到数组中的小程序来练习。但是,整数永远不会以某种方式存储并且数组是空的。
int readNumbers(int array[], char* fname) {
78
79
80 int numberRead = 0;
81 FILE* fp;
82 int ch;
83 int i = 0;
84
85
86
87 fp = fopen(fname, "r");
88 // Test to see if the file was opened correctly
89
90 if (fp == NULL) {
91 printf("Error opening file\n");
92 return;
93 }
94 // Now read until end of file
95
96 while (ch = fgetc(fp) != EOF && isdigit(ch)) {
97 array[i++] = ch;
98 }
99 if (ferror(fp)) {
100 return;
101 }
102 // Close the file pointer
103
104 fclose(fp);
105
106 // Return the number of items read
107 return numberRead;
108 }
文本文件应该是这样的:
1 2 3 4 5 6 7 8 9
提前致谢。
我已经更新了代码。这几乎可以工作,但它将 55
等字符解释为 5
和 5
。所以我的数组将有两个 5
。
while ((ch =fgetc(fp)) != EOF) {
97 if (ch != ' ' && ch != '\n') {
98 array[counter] = ch - '0';
99 counter++;
100 numberRead++;
101 }
102 }
最佳答案
要扩展 Matt McNabb 在评论中所说的话,您不能有 return
没有值(除非它在 void
函数中)。你的readNumbers()
函数被声明为返回 int
所以所有返回路径必须返回一个int。如果存在文件错误,您可能希望返回 -1,因为 0 是(有点 :) )要读取的有效字符数。
由于输入文件中的数字之间有空格,因此您需要更改 while
中的逻辑循环。
while ((ch = fgetc(fp)) != EOF && isdigit(ch))
一旦读取非数字字符就会失败。
我还应该提到,您正在将读取的每个字符的数值存储到数组中,这可能不是您想要的。例如,在 ASCII 中,“0”字符的数值为 48,“1”的数值为 49,等等。
附言。确保调用 readNumbers()
的函数提供一个足够大的数组来处理任何可能的结果...
尽量避免使用exit()
在你的程序的深处,如果可行,就在main()
中使用它.此外,而不是仅仅用 exit()
杀死你的程序最好先打印某种错误消息(通常打印到 stderr),然后然后优雅地结束。至于创建合适的错误消息,请查看 <stdio.h>
函数 perror()
,看看<errno.h>
.
您可以在 readNumbers()
中打印错误消息并返回 -1,然后让调用函数(例如 main()
)决定错误是否严重到程序应该终止。或者让调用函数也处理错误消息的打印。
关于c - 让 fgetc 工作时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227301/