c - 使用 fscanf 多个值在 C 中读取

标签 c scanf

来自以下格式的文本文件:

Name Surname ID Address
Name Surname ID Address
Name Surname ID Address

我需要提取每一个并将其放入一个变量中。

我尝试了以下两种方法:

while(fscanf(fp, "%s,%s,%d,%s\n", name2,surname2,&id2,address2) != EOF){
    printf("Name: %s, Surname: %s, ID: %d, Address: %s\n",
        &name2, &surname2, &id2, &address2);
}

这给了我错误的结果,它每行只读取一个单词,所以结果是这样的:

Name: Name Surname:@,a ID:2272012 Address: ?"
Name: Surname Surname:@,a ID:2272012 Address: ?"
Name: ID Surname:@,a ID:2272012 Address: ?"
Name: Address Surname:@,a ID:2272012 Address: ?"

And the other method I used was:

while(fscanf(fp, "%s,%s,%d,%s\n", name2,surname2,&id2,address2) == 4){
    printf("Name: %s, Surname: %s, ID: %d, Address: %s\n",
        &name2, &surname2, &id2, &address2);
}

什么都不读,什么也没有发生。

我正在读取的文件是 .dat,它用于作业,因此只能使用 .dat。

最佳答案

  • 格式字符串中不应该有逗号,除非数据中有逗号,但您没有显示。
  • 如果任何字段包含空格,这将不起作用,因为 %s 将停止。
  • 您需要显示更多输入 .dat 文件。
  • 通常最好使用 fgets() 读取整行,然后再担心解析它。

关于c - 使用 fscanf 多个值在 C 中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14199155/

相关文章:

c - 为什么函数没有将输入映射到我的变量?

c - 获取 ipaddress 的值

c - 矩阵加法程序。如果我输入一个换行符,它会跳过一行并进入第三行

c++ - 更改过滤器时 GetOpenFileName() 不刷新

c - 包含 fscanf 的程序无法编译

c - 从文件中读取数字(整数和小数),以句点作为分隔符

C Malloc 3D 数组

c - c中的用户输入

c - 以特殊方式从文件中读取 float

c - 尝试在结构上使用scanf时出现段错误