我正在学习 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 }