std::cin >> i1 >> i2;
Tells the program to read two integers, so the program looks in the stream for numbers. If you input '|', there is no number to be found and the stream is put into a failure state. The failure state will need to be clear
ed and the remainder of the bad input ignore
ed before more input can be accepted. But if you put in the numeric encoding for the character '|' (124 assuming ASCII encoding), the stream input and the conditional will both be satisfied, but now it's impossible to input the number 124 and mean 124 and not '|'.
Instead read in std::string
s. If neither of the strings are "|", test that the strings really are integers (Probably by trying to convert them to integers with std::stoi
). If you find "|", exit the loop.
MSalter's comment shook loose another solution that is much simpler than going to string
s. If 2 numbers were read, print the numbers and ask for more. Otherwise, clear the error from reading a non-integer and read in a char
to test for '|'. Here is a really simple and ugly cut:
#include <iostream>
int main()
{
int i1 = 0;
int i2 = 0;
char ch = ' '; // can be anything but |
do
{
std::cout << "Enter some nums YO (enter | to exit)\n";
if (std::cin >> i1 >> i2)
{ // we got nums, YO.
std::cout << i1 << i2; // print the nums, YO
}
else
{ // not nums, YO. Let's see if we got a |
std::cin.clear(); // clear the error
std::cin >> ch; //read for a '|'
}
} while (ch != '|' && std::cin); // loop until | is read or cin can't read a char
}
It's ugly because input like "auoaioafksdjnfkm" will print out a prompt for each character and "klasdjfahs12938 2093854sjfljzlkfjzlk" will print out excessive prompts and a "129382093854" somewhere in the middle.