grazik
grazik

Reputation: 13

Finding new line char c++

I'm making a calculator and it returns the result if it finds char print. But if the user input enter nothing happens, so i would like to add to this function (below) that if it finds new line char it would return Token print.

char ch;
cin >> ch;          

switch (ch) {
case '\n':               // i made this but it s not working
    return Token(print); // 
case print:
case ',':
case '!':
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
case '%':
case '=':
    return Token(ch); 
case '.':             
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':    
{
              cin.putback(ch);
              double val;
              cin >> val;     
              return Token(number, val);
}
default:
    if (isalpha(ch)) {
        string s;
        s += ch;
        while (cin.get(ch) && (isalpha(ch) || isdigit(ch) || ch == '_')) s += ch;
        cin.putback(ch);
        if (s == declkeyz) return Token(zmienna); 
        if (s == declkeyc) return Token(stala); 
        if (s == pierw) return Token(pier);
        if (s == poteg) return Token(pot);
        if (s == kon) return Token(quit);
        return Token(name, s);
    }
}

Upvotes: 1

Views: 121

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

It's because the input operator >> by default skips whitespace.

Use std::noskipws input manipulator to change the behavior.

Edit

Addressing OP's comment about isspace() they could do:

cin >> noskipws >> ch
if (isspace(ch)) {
    // handle white space case
}
switch(ch)
...

Upvotes: 2

Related Questions