Reputation: 1
I'm trying to solve the question in programming : principles and practice using c++
Q. make a code that reads two int values and prints them. Make '|' input stop the program. use while loop
I have no idea to distinguish whether the input is int or '|'
Upvotes: 0
Views: 101
Reputation: 698
Here is a solution.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string value1, value2;
while(1) //infinity loop
{
cout << "Enter value one" << endl;
cin >> value1;
cout << "Enter value two" << endl;
cin >> value2;
if(value1 == "|" || value2 == "|") // the || is a logical OR. If v1 oder v2 is | break the while loop
{
break;
}
cout << value1 << " + " << value2 << " = " << (std::stoi(value1)+std::stoi(value2)) << endl; //std::stoi makes a string a number, so it means string to int
}
return 0;
}
Compile it with the c++11 flag for stdoi:
g++ -std=c++11 example.cpp -o example
PS: don't ask stackoverflow to do your homework for you. Try to learn for yourself. You will need it in the job and your colleagues will depend on you.
Upvotes: 1
Reputation: 37647
This question:
make a code that reads two int values and prints them. Make '|' input stop the program. use while loop
indicates that author doesn't know c++ well or task was stated for different language. It is also possible you didn't copy paste whole description of task.
When next character to read is |
trying reading integer value will fail, so no special check has to be done.
So just read pairs of int
values until error occurs. Special check for |
is obsolete.
int a, b;
while (std::cin >> a >> b)
std::cout << (a + b) << '\n';
Upvotes: 2
Reputation: 90
Try reading the user input as a string and checking whether it's equal to |
:
#include <iostream>
#include <string>
int main() {
std::string input;
while (input != "|") {
std::getline(std::cin, input);
// read int values here
}
}
Upvotes: 0
Reputation: 49
You can pour your input into string type variable cin >> tmp_str
. Then check if it is euqal to '|'
, if not you can convert it to integer using stoi
or any alternatives.
Upvotes: 0