Hi, I am doing a drill from the book I am learning from, and i need to run a while loop until '|' is entered. I have been trying such things as while cin >> != '|' and cin != '|' but none of them work, so I assume it can not be done this way. Could someone possibly let me know how this is actually meant to be done. How am I meant to keep taking input until '|' is entered. I have included different versions of the code I have been trying below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{
int one, two;
while (cin >> )
{
cout << "Enter 2 values \n";
cin >> one >> two;
cout << one << two;
}
system("pause");
return 0;
}
int main()
{
int one = 0 , two = 0;
char quit = '|';
while (one != quit)
{
cout << "Enter 2 values \n";
cin >> one >> two;
cout << one << two;
}
system("pause");
return 0;
This conforms to your spec (since you don't specify what to do with errant data I choose to quit, therefore I can simply process the '|' as errant data).
1 2 3 4 5 6 7 8
#include <iostream>
usingnamespace std;
int main() {
int a, b;
while (cin >> a >> b)
cout << a + b << '\n';
}
Alternatively:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main() {
for (char ch; cin >> ch && ch != '|'; ) {
cin.putback(ch);
int a, b;
if (!(cin >> a >> b)) {
cerr << "WTF?\n";
cin.clear();
cin.ignore(9999, '\n');
}
else
std::cout << a + b << '\n';
}
}
If that's Stroustrup's book, at some point he explains that any string input to an integer type will cause cin to return false, so cin >> one should stop the loop when the user enters "|" instead of an integer.