Home > Software engineering >  loop as long an user input is given
loop as long an user input is given

Time:06-20

I don't know how to write correct condition in my while loop. I want my program to loop as long as user will give an input value. So user gives values, program prints result and asks the same thing again. When user does not give any input and just presses enter i want my program to finish. Here is my code:

#include <iostream>
using namespace std;
int main(){
    int a,b;
    string symbol;
    while(true){
        cin>>symbol;
        if(symbol==" "){
            cin>>a;
            cin>>b;
            cout<<a b<<endl;
        }
        else if(symbol=="-"){
            cin>>a;
            cin>>b;
            cout<<a-b<<endl;
        }
        else if(symbol=="*"){
            cin>>a;
            cin>>b;
            cout<<a*b<<endl;
        }
        else if(symbol=="/"){
            cin>>a;
            cin>>b;
            cout<<a/b<<endl;
        }
        else if(symbol=="%"){
            cin>>a;
            cin>>b;
            cout<<a%b<<endl;
        }
    }
}

I know that this code is probably poorly written but i just want it to work.

CodePudding user response:

You are asking for line based input, you said When user does not give any input and just presses enter i want my program to finish. But the input method you are using cin >> symbol; skips all spaces and newlines. So it cannot meet your requirements.

Since you want to read lines of input you should use something that does read lines of input. That function is getline.

string line;
getline(cin, line);

But now you have another problem, how do you read the symbols and numbers from the string line?

For that you need to use an istringstream. A string stream is an object which reads from a string, instead of reading from the console like cin. Here's how to use it

#include <sstream>

string line;
getline(cin, line);
if (line.empty()) // check if any input
    break;        // and quit if not

istringstream buffer(line); // create the string stream
buffer>>symbol;             // and read the symbol from it
if(symbol==" "){
    buffer>>a;
    buffer>>b;
    cout<<a b<<endl;
}
...

See how buffer is created from the line string, and then buffer>>symbol and buffer>>a; etc are used to read from the buffer.

  •  Tags:  
  • c
  • Related