我正在学习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 }发布于 2014-10-07 01:48:07
要扩展Matt McNabb在评论中所说的内容,您不能在没有值的情况下拥有return (除非它在void函数中)。您的readNumbers()函数被声明为返回int,因此所有返回路径必须返回一个int。如果存在文件错误,您可能希望返回-1,因为0是(类:)一个要读取的有效字符数。
由于输入文件中的数字之间有空格,所以需要更改while循环中的逻辑。
while ((ch = fgetc(fp)) != EOF && isdigit(ch))
一旦读取非数字字符,就会失败。
我还应该提到,您正在将读取的每个字符的数值存储到数组中,这可能不是您想要的结果。例如,在ASCII中,'0‘字符的数值为48,'1’的数值为49,等等。
PS。确保调用readNumbers()的函数提供一个足够大的数组来处理任何可能的结果.
在实际情况下,尽量避免在程序中深入使用exit(),只需在main()中使用。而且,与其仅仅用exit()杀死您的程序石,不如先打印某种错误消息(通常是stderr),然后优雅地死去,这是 some 。至于创建合适的错误消息,请查看<stdio.h>函数perror(),并查看<errno.h>。
您可以在readNumbers()中打印错误消息并返回-1,然后让调用函数(如main())决定错误是否严重到程序应该死掉。或者让调用函数也处理错误消息的打印。
发布于 2014-10-07 01:34:50
这里的括号应该是while (ch = fgetc(fp) != EOF && isdigit(ch)),它应该是while ((ch = fgetc(fp)) != EOF && isdigit(ch)),否则您将在ch中存储fgetc(fp) != EOF的值,即eather1或0(真或假)。
发布于 2014-10-07 14:33:41
// this following code modification will handle your most recent question
int value = 0; // place to accumulate numbers
int inNumber = 0; // to avoid spurious input in array[]
// note: the following expects that 'ch' is defined as an integer
while ((ch =fgetc(fp)) != EOF)
{
if (ch >= '0' && ch <= '9') // only process numeric characters
{
value *= 10;
value += (ch - 0x30); // convert alpha to binary
inNumber = 1;
}
else
{ // break between numbers
if( 1 == inNumber )
{
array[counter] = value;
counter++;
numberRead++;
value = 0; // reset for next number
inNumber = 0;
}
}
}https://stackoverflow.com/questions/26227301
复制相似问题