【发布时间】:2019-05-12 16:12:19
【问题描述】:
我能够从单独的文件中读取字符、单词、句子和整数,但我很难从 same 文件中读取单词和整数。假设我的文件包含以下内容:
Patrice 95
Rio 96
Marcus 78
Wayne 69
Alex 67
Chris 100
Nemanja 78
到目前为止,我的部分解决方案(读取字符串)是使用fgetc() 并检查我的文本文件中的空格和/或回车以将名称与数字分开。
fgetc 的主要问题是它逐个字符地读取,因此整数不应该像这样读取。作为一种解决方法,每当读入数字时,我都会将字符转换为整数。
这是主要的代码结构:
typedef struct person {
char name[10][10];
char surname[10][10];
int age [10];
} person_t;
FILE *inp; /* pointer to input file */
char c;
int word_count = 0;
int char_count = 0;
int i = 0;
int x;
person_t my_person;
while ((c = fgetc(inp)) != EOF) {
if (c == ' ' || c == '\r') {
printf("\n");
my_person.name[word_count][char_count] = '\0'; //Terminate the string
char_count = 0; //Reset the counter.
word_count++;
}
else {
if (c >= '0' && c <= '9') {
x = c - '0'; //converting to int
my_person.age[i] = x;
printf("%d", my_person.age[i]);
i++;
}
else {
my_person.name[word_count][char_count] = c;
printf("%c",my_person.name[word_count][char_count]);
if (char_count < 19) {
char_count++;
}
else {
char_count = 0;
}
}
}
}
}
for (int i = 0; i<7; i++) {
printf("ages: %d \n",my_person.age[i] ); //never executes
}
样本输出:
Patrice
95
Rio
96
Marcus
78
Wayne
69
Alex
67
Chris
完整代码可以在pastebin找到。
为什么 for 循环从不执行?关于我可以改进以读取字符串和整数列的任何建议?
【问题讨论】:
-
感谢您的 cmets,我愚蠢地监督了这两个非常有效的观点。