【问题标题】:Reading columns of strings and integers from file从文件中读取字符串和整数列
【发布时间】: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,我愚蠢地监督了这两个非常有效的观点。

标签: c function file struct


【解决方案1】:

使用fgets() 读取整行。

char line[100];
while (fgets(line, sizeof line, inp)) {
    // got a line, need to isolate parts
}

然后,根据单词是否可以嵌入空格,选择以下策略之一。

a) sscanf() 隔离姓名和年龄

while (fgets(line, sizeof line, inp)) {
    char name[30];
    int age;
    if (sscanf(line, "%29s%d", name, &age) != 2) /* error, bad line */;
    // ...
}

b) strrchr() 查找最后一个空格,然后进行字符串操作以提取姓名和年龄。

while (fgets(line, sizeof line, inp)) {
    char name[30];
    int age;
    char *space = strrchr(line, ' ');
    if (!space) /* error, bad line */;
    if (space - line >= 30) /* error, name too long */;
    sprintf(name, "%.*s", space - line, line);
    age = strtol(space, NULL, 10); // needs error checking
    // ...
}

策略 b) 在https://ideone.com/ZOLie9

【讨论】:

  • 感谢您提供有用的见解,这更有意义。所以如果我理解正确,如果我有一个名字一个姓氏,我会使用strrch()
  • 是的,使用strrchr(),您可以轻松隔离"Foo Bar 42" 之类的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多