D
D
Demigodd2018-04-17 08:49:11
C++ / C#
Demigodd, 2018-04-17 08:49:11

How to check the output for a number?

#include <iostream>

int main() {
    int num = 0;

    while(num != -1) {
        std::cout << "Enter the number to push: ";
        std::cin >> num;
    }

    return 0;
}

There is such a code how to check the output for a number, if not a number is displayed, then exit the loop?
It's just that if you output a character, then the loop will go to INFINITY ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Ariox41, 2018-04-17
@Demigodd

Output is the output from the program to the stream (cout), input is the input from the stream to the program (cin), this can be understood by the names.
One of the options is to read not purely, but a string, and then convert the string to purely other functions.
Or you can use the thread error handling interface:

#include <iostream>
#include <limits>

int main() {
    int num = 0;

    while(num != -1) {
        std::cout << "Enter the number to push: ";
        std::cin >> num;
        if(std::cin.fail()){
            std::cout  << "It is not number" << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<int>::max(), '\n');
        } else{
            std::cout << "num = " << num << std::endl;
        }
    }
    
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question