【问题标题】:get-line gets always the same line C++get-line 总是在同一行 C++
【发布时间】:2021-09-19 23:29:39
【问题描述】:

我有一个包含这样数据的文件

10000 9.425 1.00216 -0.149976
20000 19.425 0.973893 -0.135456
30000 29.425 1.01707 -0.115423
40000 39.425 1.0181 -0.12074
.
.
.

要获取数据,我正在做的是读取整行,然后用空格分隔行以获取我需要的数据。问题是该文件有 3000 行,所以我试图在 for 循环中获取该行

  std::vector<std::string> a;
  std::ifstream datas("Data/thermo_stability.dat");
  std::string str;
  char d=' ';
  for(int i=0; i<n; i++)
    {
      std::getline(datas, str);
      tokenize(str,d,a);
      x[i]=std::atof((a[1]).c_str());
      y[i]=std::atof((a[3]).c_str());
      std::cout << x[i] << "\t" << y[i] << std::endl;
    }

我注意到出了点问题,所以我添加了那个 cout,发现它总是在同一行。我该如何解决这个问题?为什么在调用 getline 后没有得到下一行?当我在循环之外执行它时,它会转到下一行。

编辑

这是标记化的函数

void tokenize(std::string &str, char delim, std::vector<std::string> &out)
{
  size_t start;
  size_t end = 0;
  
  while ((start = str.find_first_not_of(delim, end)) != std::string::npos)
    {
      end = str.find(delim, start);
      out.push_back(str.substr(start, end - start));
    }
}

【问题讨论】:

  • 你怎么知道它没有得到下一行。您不会打印出str。看起来更像 tokenize() 无法将字符串读入 a 但我们无法判断,因为您没有显示该功能。
  • edit 这个问题包含minimal reproducible example。此代码可能工作或失败,具体取决于此处未显示的部分。
  • 我添加了tokenize功能。

标签: c++ file c++11 getline


【解决方案1】:

该代码有一些问题:

我看不到n 的设置位置,所以你怎么知道它是正确的。读取一行的正确方法是调用getline(),然后测试它是否有效(可以在一行中完成)。

 while(std::getline(datas, str)) {
     // Successfully read a line from the file
 }

您不需要手动将字符串转换为整数或浮点数。流库会自动执行此操作。

    std::istringstream lineStream(std::move(str));
    str.clear();

    int value1;     // please use better names:
    double value2;
    double value3;
    double value4;

    lineStream >> value1 >> value2 >> value3 >> value4;

【讨论】:

  • 我尝试了 std::stringstream lineStream 并且编译器说 std::stringstream lineStream' 具有初始化程序但类型不完整。另外,不知道 line.clear 和 std::move 是什么。我是否必须包含其他一些库才能使用它?
  • 在解析输入时首选使用std::istringstream。并且不需要clear()一个新构造的流对象。
  • @RemyLebeau 我正在清除原始字符串。移动后,它处于有效但未定义的状态。只需确保它是空的(处于有效且已知的状态)。
  • @MartinYork 你move'd 字符串,所以没有什么要清除的。
猜你喜欢
  • 2022-12-01
  • 2016-01-07
  • 1970-01-01
  • 2012-05-18
  • 2013-04-10
  • 2020-04-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多