【问题标题】:Trouble reading a comma-terminated string in无法读取以逗号结尾的字符串
【发布时间】:2016-05-01 05:11:27
【问题描述】:

我有一个函数可以将如下所示的文件读入结构中。我正在努力确保结构被正确填充;并且,它正确填写了性别、身高和体重。但是,我无法验证其中的名称(字符数组)部分是否正确填写。

要读入的示例文件:

Name,Gender,Height,Weight
Tanner,M,71.8,180.25
John,M,70.75,185.3
Parker,F,65.25,120.3
Meeks,M,57.25,210.2
Big,M,57.5,150.1
Jackson,F,52.1,163.4

结构定义:

struct canData
{
    char name[50];
    char gender;
    float height;
    float weight;
}CD[structSize]; // end struct BP

读取文件的循环部分:

char name[50];
    char gender;
    float height;
    float weight;
    int position = 0;

filePtr = fopen(fileName, "r"); // open file
    if (filePtr == NULL) // error check opening file
    {
        printf("Opening file failed. Please reenter filename.");
        exit(1); // WILL THIS RETURN TO MENU?
    } // end if

// skip header line of file
    char buffer[100];
    fgets(buffer, 100, filePtr);

while (fscanf(filePtr, "%[^,], %[^,], %f, %f", &name, &gender, &height, &weight) == 4) // read in
    {
        printf("%s\n", name); // DEBUG ATTEMPT
        printf("%s\n", CD[position].name); // DEBUG ATTEMPT
        printf("%f\n", weight); // DEBUG ATTEMPT

        strcpy(CD[position].name, name);
        CD[position].gender = gender;
        CD[position].height = height;
        CD[position].weight = weight;
        position++;
        iCount++;



    } // end while

目前,我的输出如下:

(space where name should be)
(space where CD[position].name should be)
180.25
(space where name should be)
(space where CD[position].name should be)
185.3
(space where name should be)
(space where CD[position].name should be)
120.3
(space where name should be)
(space where CD[position].name should be)
...

感谢您的任何见解!我是 C 初学者,所以我可能会错过一些愚蠢的东西。

【问题讨论】:

  • namegenderheightweight 的类型是什么?您确定您没有通过将指针传递给具有错误类型的对象来调用 未定义的行为
  • 你确定CD[position].name在DEBUG ATTEMPT初始化了吗?请发帖Minimal, Complete, and Verifiable example
  • 你打印CD[position].name 之前 strcpy。另外,试试while (fscanf(filePtr, " %[^,], %[^,], %f, %f", name, gender, &height, &weight) == 4)
  • gender 只能存储一个字符,因此考虑到终止空字符,只能读取零个字符。
  • @MomoDevi 似乎它似乎工作正常。不要访问未分配的位置。使用%c 读取单个字符。

标签: c string comma


【解决方案1】:

scanf 在读取字符串时需要一个指向数组初始字节的指针。所以当你作为参数传递时不要使用&fscanf(fp, "%[^,]", name) 应该可以工作。

name 在表达式中使用时将转换为指针。

http://pubs.opengroup.org/onlinepubs/009695399/functions/fscanf.html

【讨论】:

  • "name 本身就是你代码中的一个指针。"不,name 不是指针而是数组。表达式中使用的数组通常会转换为指向其第一个元素的指针。常用的异常有sizeof 运算符和一元& 运算符的操作数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 2012-08-29
相关资源
最近更新 更多