【问题标题】:Reading a txt. in the format of (int float float string) and putting the values into parallel arrays读一个txt。采用 (int float float string) 格式并将值放入并行数组
【发布时间】:2015-11-21 00:54:01
【问题描述】:
1 42.4 73.45 Albany, N.Y.
2 35.05 106.39 Albuquerque, N.M.
3 35.11 101.5 Amarillo, Tex.
4 61.13 149.54 Anchorage, Alaska
5 33.45 84.23 Atlanta, Ga.
6 30.16 97.44 Austin, Tex.

给定一个 int float 浮点字符串格式的 .txt 文件中这样的表格,我必须读取该文件并将数据放入相应的数组中。

数据必须输入到并行数组中

  • 第 1 列是城市标识

  • 第 2 列是 x 位置

  • 第3列是y位置

  • 第 4 列是城市名称

我可以读取数组,但我不知道如何将数据放入相应的数组中。

我尝试过使用

while ((fscanf(filePtr, "%d %f %f %[^'\n']", cityid, x_location, y_location, city_name)) == 4)

但是循环遍历整个文件并且只将最后一个条目放入数组中。

所以我尝试了这个循环

while (fscanf(filePtr, "%d %f %f %[^'\n']", tcityid, tx_location, ty_location, cityname) == 4)

    {
        cityid[i] = tcityid;

        x_location[i] = tx_location;

        y_location[i] = ty_location;

        *city_name[i] = cityname;           

    }

所以我的想法是 fscanf 将读取一行并将每个值放入相应的变量中,然后将其复制到数组中。我的代码将构建并运行,但是当它到达 while 循环时,它会抛出一个错误,提示

一个无效参数被传递给一个认为无效参数致命的函数。

我认为问题出在city_name,我不确定如何处理。任何帮助将不胜感激。 谢谢你

【问题讨论】:

    标签: c arrays pointers file-io char


    【解决方案1】:

    问题是 scanf 不接受格式规范中的正则表达式。此外,您不能只使用 %s,因为它在第一个空格处停止,因此状态名称将被截断。我能建议的最好的方法是你使用 fgets() 在一行中读入一个名为“line”的字符串。然后使用 sscanf 提取前三个数字。然后使用 strchr 3 次找到第三个空格,这是城市名称的开始。最后使用 strdup() 复制可以存储在数组中的城市名称。您不能简单地将指针保存到“行”中,因为每次读取新行时都会覆盖行。

    【讨论】:

    • 忘了说:这只是一个大纲。在实际代码中,当数据格式错误时,您应该防止缓冲区溢出。众所周知,字符串操作很容易搞砸,并且很容易造成安全漏洞......
    • 我们不允许在 string.h 中使用函数,但我可以使用 fgets() 来解决。拉出各个行使我更容易理解我需要做什么再次感谢您的帮助。
    【解决方案2】:

    错误的参数传递给fscanf()

    我很惊讶你的编译器没有警告这一点。检查编译器设置或考虑使用新的编译器。

    传递intfloat 值的地址

    同时修改[] 说明符。

    // while (fscanf(filePtr, "%d %f %f %[^'\n']", 
    //   tcityid, tx_location, ty_location, cityname) == 4)
    while (fscanf(filePtr, "%d %f %f %[^\n]", 
      &tcityid, &tx_location, &ty_location, cityname) == 4)
    

    顺便说一句,@LaszloLadanyi 想法很好,使用fgets() 读取行,然后使用sscanf()

    【讨论】:

      猜你喜欢
      • 2015-07-17
      • 2017-02-03
      • 1970-01-01
      • 2017-03-04
      • 2017-02-12
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多