stringstream 仅适用于一行,然后在重复使用时中断

stringstream only works for one line then breaks when reused

我正在尝试读取一个名为 trajectory.txt 的简单文件(在下面进行了简化),它看起来像这样:

true true false
2

我的代码很简单,读入前两行并将其存储在一些变量中。

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

int main(int argc, char** argv)
{

int num_waypoints=0;
bool pos=1, vel=0, acc=0;
std::ifstream file;
std::string filename = "trajectory.txt";
file.open(filename.c_str());
std::string line;

// Read first 2 lines
if (std::getline(file, line)) {

  //sstream for each line
  std::stringstream ss(line);

  //first line
  std::string pos_str, vel_str, acc_str;
  ss >> pos_str >> vel_str >> acc_str;

  //evaluate
  (pos_str == "true" ? pos = true : pos = false);
  (vel_str == "true" ? vel = true : vel = false);
  (acc_str == "true" ? acc = true : acc = false);

  //second line
  if (std::getline(file, line)) {               //GDB confirms, line == "2"
    std::string num_waypoints_str;              
    ss >> num_waypoints_str;                    //THIS DOES NOTHING?
    num_waypoints = stoi(num_waypoints_str);
}

} //main()

问题是在倒数第二行,num_waypoints_str 在 stringstream 应该读入值后留空。

使用 GDB 我能够确认 stringstream 确实取了“2”的值,但似乎在将值指向 num_waypoints_str.

时遇到了问题

因此我只有两个问题:

  1. 为什么字符串流不将其值传递给字符串? (是否与在新范围内有关)
  2. 我的代码可以简化为直接从字符串流输入第 1 行到布尔值 pos 还是我必须通过评估字符串的值从字符串 pos_str 转换为 pos

我正在通过 g++ -g -std=c++11 main.cpp -o main 编译。请尝试复制我的问题。我觉得我缺少一些简单的东西。

stringstream 并没有神奇地绑定到您的 std::string line;:

   //second line
   if (std::getline(file, line)) {               //GDB confirms, line == "2"
     std::string num_waypoints_str;              
     ss >> num_waypoints_str;                    //THIS DOES NOTHING?
     num_waypoints = stoi(num_waypoints_str);

ss 仍然具有其在构造函​​数中早于此设置的值。更准确地说:

std::stringstream的constructor复制了你给它的字符串,它不绑定到它。

如果您不想再构造一个,可以使用 std::basic_stringstream::str 更新 ss 的内容。 注意:与其他流一样,stringstreams 也有标志,例如 eof,这些也需要重置。所以在你的情况下它是:

    ss.clear();
    ss.str(line);

非常接近答案。您还需要在重新使用之前清除字符串流。

//first use
getline(file, line);
stringstream ss(line);
ss.clear()

//second use
getline(file, line);
ss.str(line);