I want to take input from the user in a string and insert those values into a vector using stringstream
my code looks like this :
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main (){
string s;
getline(cin ,s);
vector<int>vec;
istringstream iss{s};
while(iss){
int temp;
iss>>temp;
vec.push_back(temp);
}
for (auto val:vec){
cout << val<<" ";
}
return 0;
}
I am inserting 1 2 3 in the string but the output is 1 2 3 3 . this method is inserting the last
element 2 times.
but the following is working fine :
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main (){
string s;
getline(cin ,s);
vector<int>vec;
istringstream iss{s};
do{
int temp;
iss>>temp;
vec.push_back(temp);
}while(!iss.eof());
for (auto val:vec){
cout << val<<" ";
}
return 0;
}
can anyone tell why the first method is taking the last input twice?