I am having trouble converting a string of numbers from a file, say 1 2 55 -44 22
into an integer array.
My program so far works except for one bug, it interprets integers like 55
as 5
and 5
.
int readNumbers(int array[], char* fname) {
78 // TODO: will you read the comments above this function carefully???
79 // TODO: note those pre- and post-conditions!
80 int numberRead = 0;
81 FILE* fp;
82 int ch;
83 int counter = 0;
84
85 // Use fopen to try to open the file for reading
86 // TODO:
87 fp = fopen(fname, "r");
88 // Test to see if the file was opened correctly
89 // TODO:
90 if (fp == NULL) {
91 printf("Error opening file\n");
92 return -1;
93 }
94 // Now read until end of file
95 // TODO:
96 while ((ch = fgetc(fp)) != EOF) {
97 if (ch != ' ' && ch != '\n') {
98 array[counter] = ch - '0';
99 counter++;
100 numberRead++;
101 }
102 }
103 if (ferror(fp)) {
104 fclose(fp);
105 return -1;
106 }
107 // Close the file pointer
108 // TODO:
109 fclose(fp);
110
111 // Return the number of items read
112 return numberRead; // can it be negative? if in doubt, read.
113 }
I've looked elsewhere and many use fgets? I'm not sure if that would make a difference and want to hear opinions before making a change.