0

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)
DVD_DAVIDE
  • 11
  • 4

1 Answers1

0

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • Thanks, it works. I was trying to do that in another program, but it doesn't work. Could you explain me why? `while(std::getline(std::cin, input) && input != "c" && input != "C") { myfile << input << "\n"; };` P.S: _myfile_ is declared as `std::fstream myfile;` – DVD_DAVIDE May 14 '20 at 10:14
  • @DVD_DAVIDE Presumably you need to change `std::cin` to `myfile` but I can't say for sure without a better explanation of the problem than "doesn't work" and it would also help to see the complete source code. – cdhowie May 16 '20 at 04:27