how to save a whole sentence

May 30, 2017 at 7:12pm
I have this kind of file:

1 hello
2 hello world
3 hello my world


I read this file with getline(file, line) to save, with the use of stringstream, number in a vector of int and the rest of line in a string. The problem is created by the spaces between the words!
Can anyone help me?
May 30, 2017 at 7:30pm
Hello Faggio,

Post your code so all can see what you have done and figure what you can do. Otherwise it is just a guess.

If you are using a stringstream I would consider reading the stringstream this way:
1
2
3
4
5
6
7
ss >> num;

while(std::getline(ss, line, " "))

    fullString += line + " ";

fullString.pop_back();  // <--- Removes last " " (space) 


Untested, but I think it should work.

Hope that helps,

Andy
May 30, 2017 at 8:00pm
ok, i can try to post my code but it's little bit complicated.

1
2
3
4
5
6
7
8
9
10
11

 while(getline(fin1, line))
   {
       Answer <int> fil;
       is<<line;
       is>>fil;
       is.clear();
       answList.push_back(fil);

}




Note that fin1 is a file, line is a string, fil is a template class, "is" is a stringstream and answList is a list. I have implemented the operator ">>" in the Answer class in this way :
1
2
3
4
5
6
7
8
9
10
11
12

friend istream& operator >>( istream& is, Answer <T> &a)
    {
        is >> a._id;
        is.ignore();
        is >> a._text;
        is.ignore();
        return is;
    }





May 30, 2017 at 8:03pm
One way to do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int main()
{
  vector<int> numbers;
  vector<string> lines;

  ifstream src("input.txt");
  if (!src)
  {
    perror("ERROR: ");
    return -1;
  }
  int num =0;
  string line;

  while (src >> num)
  {
    numbers.push_back(num);
    getline(src, line);
    lines.push_back(line);
  }
  cout << "Data read:";
  cout << "\n\nNumbers: ";
  cout << "\n--------";
  for (int num: numbers)
    cout << "\n" << num << " ";
  cout << "\n\nLines: ";
  cout << "\n------";
  for (string l : lines)
    cout << "\n" << l << "\n";

  system("pause");
}
May 30, 2017 at 9:05pm
If the leading spaces are a problem, you can also add something like this:
line.erase(line.begin(), line.begin() + line.find_first_not_of(' '));

to Thomas1965's worthy code, before
lines.push_back(line);
Topic archived. No new replies allowed.