Reputation: 281
I am converting a String to an integer and then passing to a vector and then print it but the first element of the string does not get printed.
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
stringstream ss(str);
vector<int> my;
char ch;
int num;
while(ss.good()){
string substr;
getline(ss, substr, ',');
ss >> num;
my.push_back(num);
}
return my;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
Upvotes: 0
Views: 118
Reputation: 96810
The main issue is the ss >> num
line. We first start with 1,2,3,4,5
in the stream. getline(ss, substr, '\n')
reads the first number from the stream (1
) and gets rid of the delimiter ,
. Then ss >> num
reads the next number (2
) but keeps the next ,
in the stream because the formatted operator >>
only reads as many characters that are valid for the type its being read into. So you threw away the 1
that was stored inside substr
and pushed in 2
to the vector.
So the stream at this point is ,3,4,5
by the second iteration of the loop. getline
reads an empty string into substr
(because there's no number before the ,
) and gets rid of the the delimiter ,
and ss >> num
reads 3
. This repeats until the entire stream is read: getline
constantly reads an empty string and ss >> num
reads in the integer.
The solution is to get rid of the ss >> num
line and convert substr
to an integer with std::stoi
. Also, as a matter of correctness you should put the input operation into the condition of the while
loop. This way the loop is entered after checking if the input operation succeeded.
std::string substr;
while (getline(ss, substr, ',')) {
my.push_back(std::stoi(substr));
}
Upvotes: 2