私は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
。したがって、私の配列には 2 つ5
の があります。
while ((ch =fgetc(fp)) != EOF) {
97 if (ch != ' ' && ch != '\n') {
98 array[counter] = ch - '0';
99 counter++;
100 numberRead++;
101 }
102 }