Colette Cleveland Colette Cleveland - 1 month ago 21
C++ Question

char not terminating while loop

Okay I have a while loop going on to add chars from one string to a new string and it's supposed to terminate once it reaches a certain character mainly ' ' but instead it continues endlessly. heres a piece of the program

istringstream istr(str);
char token;
istr>> token;
string t;
t.push_back(token);
istr>>token;
while(token != ' ' && token != '+' && token != '-'){
t.push_back(token);
istr>>token;
}

Answer

Loop will work infinite if str starts with ' ', '+' or '-'. You will skip the first token. To avoid it you shouldn't read two tokens before loop:

...
istr>> token;
string t;         
// t.push_back(token); // what if it's ' ' or '+'
// istr>>token; // do not read second time
while(...

And the second case is an empty str. You should check if it's empty and do not process it in this case.


Also can do it without istringstream:

string str = ...;
string t;
for(char token: str) {
    if(token == ' ' || token == '+' || token == '-')
        break;
    t.push_back(token);
}

In case if you want to continue from the place where you've stopped, you can use indexes:

string str = ...;
string t;
int i = 0;

for(; i < str.size(); ++i) {
    if(str[i] == ' ' || str[i] == '+' || str[i] == '-')
        break;
    t.push_back(str[i]);
}

// some other code

++i; // skip ' ', '+' or '-'
string t2;

for(; i < str.size(); ++i) {
    if(str[i] == ' ' || str[i] == '+' || str[i] == '-')
        break;
    t.push_back(str[i]);
}
Comments