Search code examples
c++while-loopcharistringstream

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. 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;
}

Solution

  • 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]);
    }