1
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main() {
string str;
getline(cin,str);
stringstream ss(str);
vector<int> arr;
while(!ss.eof()){
    int num;
    char ch;
    ss>>num>>ch;
    arr.push_back(num);
}
for(int i=0;i<arr.size();i++){
    cout<<arr.at(i)<<endl;
}
return 0;

}

I am getting output for 1,2,3,4,5 as 1 2 3 4 5 but for 1 2 3 4 5 it is 1 3 5 why? space is also a character so it should work or am I missing something? thank you for helping.

  • Have you ever wondered why `int a,b; cin>>a>>b;` works if input is say `1 2`? What happens to that space? – theWiseBro Feb 13 '20 at 14:36
  • `while(!ss.eof()){` -- [Don't do this](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – PaulMcKenzie Feb 13 '20 at 14:37

2 Answers2

0

Because formatted input operations skip whitespaces. Thus the following happens:

ss >> num // reads integer 1
   >> ch; // skips whitespace after 1 and reads char '2'

In the next iteration:

ss >> num // skips whitespace after 2 and reads integer 3
   >> ch; // skips whitespace after 3 and reads char '4'

And the last iteration:

ss >> num // skips whitespace after 4 and reads integer 5
   >> ch; // Encounters eof, nothing is read

Don't read that char for space-seperated lists. Or You can use std::noskipws to change this behaviour.

churill
  • 9,299
  • 3
  • 13
  • 23
0

Extraction operator “>>” provides reading space separated integers without reading a separator by:

ss >> num; 

instead of additional reading of separator in original code:

ss >> num >> ch;

because for standard streams, the skipws flag is set on initialization. And this makes more simple reading space separated integers.

To make both separators working similar add

ss >> noskipws;

as in following code:

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main () {
  string str;
  getline (cin, str);
  stringstream ss (str);
  ss >> noskipws;
  vector<int> arr;
  while (!ss.eof ()) {
    int num;
    char ch;
    ss >> num >> ch;
    arr.push_back (num);
  }
  for (int i = 0; i < arr.size (); i++) {
    cout << arr.at (i) << endl;
  }
  return 0;
}
Val
  • 121
  • 1
  • 4