0

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. Here's 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;
}
kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
  • 1
    add `istr &&` into the `while` condition, so that it detects input failure – M.M Oct 28 '16 at 00:46
  • If you want iterate on a string in cpp look this [question](http://stackoverflow.com/questions/9438209/for-every-character-in-string) – Stargateur Oct 28 '16 at 00:47
  • If `istr` reachs end of file of there's any failure, any subsequent `>>` is a no-op and doesn't write anything. So, `token` isn't change and the `ẁhile` condition will yield the same result at every loop. That's why it continues endlessly. – ABu Oct 28 '16 at 01:06

1 Answers1

3

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(...

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

Also if str doesn't contain ' ', '+' or '-', loop will not stop. To stop it at the end of istr, add case istr to while. When the end is reached, istr'll become false and the loop will stop.


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]);
}
Pavel
  • 5,374
  • 4
  • 30
  • 55