I'm trying to make a program that outputs random numbers between 1 and 21 with a loop. To exit the loop, you've to digit 'c' or 'C' and I want to make it continue the loop by pressing only ENTER, but the cin function doesn't accept a null input. Could you help me?
The code is like this:
char input[100];
int number;
do{
//reset the variable
input[]=null;
cin>>input;
if(input){
number=rand()%21+1;
}
cout>>number;
} while (input)
Use std::string
instead of a char array, and then use std::getline()
to get exactly one line.
std::string input;
while (std::getline(std::cin, input) && input != "c" && input != "C") {
std::cout << (rand() % 21 + 1) << '\n';
}
As an aside, it looks like you're using using namespace std;
. Don't do that.