I'm going through Bjarne Stroustrup's 'Programming : Principles and Practice using C++" and I've got a drill which tells me to write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them and that it should exit when "|" is entered. I've written the program(I'm sure there's a easier way of writing it, but I've got the "gift" of overcomplicating things), but I can't find a way of exiting the loop. Here's the code:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> answers;
int answer;
int intCounter=0;
while(answers.size()<=2 )
{
if(answer=='|')
{
return 0;
}
std::cin>>answer;
answers.push_back(answer);
++intCounter;
if(intCounter==2)
{
for(int x : answers)
{
std::cout<<x<<'\n';
}
answers.clear();
intCounter=0;
}
}
return 0;
}
Basically if I write an if statement to check if answer is equal to '|', the compiler thinks i meant the int value of it(124 or something like that) and terminates the loop when I write 124, and that's clearly not what I want. I've tried to look over the internet for a way of converting an int into a char, but I haven't understood anything from there. The simplest solution would be the best.
cin >> answer
will fail when the next non-whitespace character to be read is not a number. You can use that behavior to end the loop.
// Break inside the loop.
while( true )
{
std::cin>>answer;
// If there was an error in reading, break out of the loop.
if ( !std::cin )
break;
answers.push_back(answer);
++intCounter;
if(intCounter==2)
{
for(int x : answers)
{
std::cout<<x<<'\n';
}
answers.clear();
intCounter=0;
}
}
Two changes:
If your task is to just print numbers you could just use string.
You are checking value of answer to |
before its even been input. So
#include<iostream> #include <vector> #include<string> using namespace std; int main(){ std::vector<string> answers; string answer; int intCounter=0; while(answers.size()<=2 ){ std::cin>>answer; //after input if(answer=="|"){ return 0; } answers.push_back(answer); ++intCounter; if(intCounter==2){ for(int x=0;x< answers.size();x++){ std::cout<<answers[x]<<'\\n'; } answers.clear(); intCounter=0; } } return 0; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.