Reputation:
while(getline(data, word, '\n')){//seperates by line
ss<<word; // output1: Chicken, for sale, 60
// output2: Microwave, wanted, 100 (and so on)
while(getline(ss, word, ',')){//seperates by individual words + space
// output1: Chicken
// output2: for sale
// output3: 60
if(word[0]==' '){ //removes space in 2 and 3
word.erase(0,1);
}
if(wordindex==0){
board[i].object=word;
wordindex++;
}
else if(wordindex==1){
board[i].type=word;
wordindex++;
}
else if(wordindex==2){
board[i].price=word;
wordindex=0; //resets index to 0 for next line
i++; //moves to next struct in array
}
}
}
The second getline loop only loops once for the first input: chicken, for sale, and 60
and does not reach the second. I figure word index is always set to 0
so it shouldn't be a problem. Also, the first getline()
outputs all data entirely, so something is causing the second getline()
to get confused. I just can't see what it is.
Upvotes: 1
Views: 253
Reputation: 33932
Here
ss<<word;
OP reuses a stringstream that may have been read to the end on a previous iteration, setting the stream into a bad state where it can no longer be written to or read from. This can be resolved by adding
ss.clear();
at the end of the loop to remove any bad flags, but by constantly writing mor data into the stringstream it will continue to grow, soaking up more and more memory unless emptied out with something like
ss.str(std::string());
to set it's internal buffer back to an empty string. It might be better to just create a new stringstream
each iteration just for code clarity if the added cost of construction and destruction to the parsing speed is not an issue.
Here is one simpler approach to the inner parsing loop:
std::stringstream ss(word);
while(i<MAX_ARRAY_SIZE && // prevent overflow
getline(ss, board[i].object, ',') &&
getline(ss, board[i].type, ',') &&
getline(ss, board[i].price, ',')){ // read all three parameters directly into object
//sanitize
if(board[i].type[0]==' '){
board[i].type.erase(0,1);
}
if(board[i].price[0]==' '){
board[i].price.erase(0,1);
}
i++; // next, please
}
Upvotes: 2