dimanche 26 juin 2022

std::stringstream segfaullts and >> operator doesn't work as intended [closed]

I am reading pairs of words from a file and inserting them in some Data structures to measure perfomance. I initially had this piece of code and everything was working great.

for (std::string line; std::getline(file, line);) {
  std::stringstream iss(line);
  while (iss >> s) {
     //insert etc
  }
}

However to boost perfomance I moved the stringstream outside the loop and used .str() to set the contents to avoid constructor-destructor calls in each line. Now my stringstream reads everything fine but the inner while loop stops running after exactly 1 std::line. In the following code std::getline() reads the contents correctly,and also iss.str() has the contents from the line correctly,but the inner loop stops running and I get a segfault in the end. Any ideas? Heres the code

std::stringstream iss;
std::string s;
for (std::string line; std::getline(file, line);) {
  iss.str(std::move(line));
  std::cout << "ss: " << iss.str() << '\n'; // Has contents
  while (iss >> s) { // doesn't run in the 2nd iteration of for-loop
    std::cout << "s: " << s << '\n';
    token = Edit(s);
    if (token.empty() || tmp.empty()) continue;
    pf = PairFrequency(tmp, token);
    Insert();
    tmp = token;
  }
}

Aucun commentaire:

Enregistrer un commentaire