我正在学习C,并通过编写一个小程序来读取文本文件中的整数并将它们存储到一个数组中。但是,整数永远不会以某种方式存储,并且数组为空。无法获得fgetc的工作
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
's。
while ((ch =fgetc(fp)) != EOF) {
97 if (ch != ' ' && ch != '\n') {
98 array[counter] = ch - '0';
99 counter++;
100 numberRead++;
101 }
102 }
将'ch = fgetc(fp)!= EOF'改为'(ch = fgetc(fp))!= EOF'。比较运算符的优先级高于赋值。 – 2014-10-07 01:34:23
您的函数在没有关闭文件的情况下返回,以防'有点奇怪的'ferror'。 “无回应”也是非法的,没有争论。 – 2014-10-07 01:35:21
@MattMcNabb谢谢! – mrQWERTY 2014-10-07 01:37:14