#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.
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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.