我很难将文件中的数字字符串转换成整数数组,比如1 2 55 -44 22。
到目前为止,我的程序除了一个bug之外,它将像55这样的整数解释为5和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 } 我找过其他地方很多人用烟丝?我不确定这是否会产生影响,并希望在作出改变之前听取意见。
发布于 2014-10-07 03:24:46
下面是如何使用fgets来完成这一任务
char arr[PickYourSize];
char* ptr;
fgets(arr , sizeof arr , fp);
ptr = strtok(arr , " ");
while(ptr)
{
array[counter++] = strtol(ptr , NULL , 10);
++numberRead;
ptr = strtok(NULL , " ");
}发布于 2014-10-07 03:22:39
您正在使用fgetc。它将进行字符阅读。因此,为了满足您的要求,您正面临着麻烦。我请求您使用fscanf,这也是一种简单的方法。
如果fscanf在匹配任何参数之前失败,它将返回EOF
示例代码
int main ()
{
FILE *fp = fopen ("/home/inputs.in", "r");
int d=0;
while ( EOF != fscanf ( fp, "%d ", &d ))
{
printf ("%d ", d);
}
return 0;
}https://stackoverflow.com/questions/26228031
复制相似问题