1

First off, I am very new to C++ (I literally started learning it 2 hours ago, so go easy on me)

This simple program is supposed to check whether or not the user input is a valid number between 0 and 101 and simply respond, valid or invalid.

#include <iostream>

int main() {
    
    bool isValidNum = false;
    do 
    {
        std::cout << "How many samples were collected?\n";

        int numOfSamples;
        std::cin >> numOfSamples;
        
        isValidNum = (numOfSamples > 0 && numOfSamples < 101);

        if (isValidNum) {

            std::cout << "valid\n";
        }
        else {

            std::cout << "invalid\n";
            
        }

    } while (isValidNum == false);
    

} 

It works. Except that if you put anything other than an integer it loops infinitely.

I may have over stretched myself by using a do/while loop whilst so unfamiliar with this language.

What is wrong with the condition flow? (I assume i'm just being incredibly smoothbrained and need some coffee)

4Ves
  • 53
  • 8
  • 4
    Does this answer your question? [Why would we call cin.clear() and cin.ignore() after reading input?](https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input) –  Sep 07 '20 at 09:24
  • 2
    `(numOfSamples > 0 && numOfSamples < 101) ? true : false` is exactly the same as `(numOfSamples > 0 && numOfSamples < 101)`. – Elliott Sep 07 '20 at 09:35
  • Thanks guys, I was having a smoothbrain moment. That'll teach me to try and code at like 6 AM. – 4Ves Sep 07 '20 at 09:56
  • @GeorgeAmos, you can post an answer to your own question (don't put the answer in the question). – Elliott Sep 07 '20 at 10:32
  • 1
    Fixed that paragraph. – 4Ves Sep 07 '20 at 11:00

1 Answers1

0
   #include <iostream>
#include <string>
using namespace std;

int main() {

    bool isValidNum = false;
    string input;
    int numOfSamples;
    std::cout << "How many samples were collected?\n";
    do
    {
        getline(cin, input, '\n');
        if (input == "")continue;
        numOfSamples = atoi(input.c_str());
        isValidNum = (numOfSamples > 0 && numOfSamples < 101);
        if (isValidNum) {

            std::cout << "valid\n";
        }
        else {

            std::cout << "invalid\n";
        }
    } while (isValidNum == false);
}