Ahmad Al-Deeb
Ahmad Al-Deeb

Reputation: 33

Getting output many times in C++

#include <iostream>

int main() {
    int fav_num {0};
    bool in_range {false};

    while (in_range == false) {
        std::cout << "Enter your favorite number between 1 and 100: ";
        std::cin >> fav_num;

        if (fav_num < 1 || fav_num > 100 || !std::cin ) {
            std::cout << "===Ops!, invalid choice, please try again.===" << std::endl;
            std::cin.clear();
            std::cin.ignore();
        }
        else {
            std::cout << "Amazing!! That's my favorite number too!" << std::endl; 
            std::cout << "No really!!, " << fav_num << " is my favorite number!" << std::endl;
            in_range = true;
        }
    }
    std::cout << "==================================================" << std::endl;
    return 0;
}

Why am I getting my output many times?

screenshot

Upvotes: 3

Views: 134

Answers (1)

Max Vollmer
Max Vollmer

Reputation: 8598

Once for q, once for w, once for e.

Check the docs for std::basic_istream::ignore. Without parameter, it skips only one character, so your loop will go through each character once, before it accepts new input again.

You want std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); to ignore every character until the next line.

Upvotes: 4

Related Questions