Check if the input is a number or string in C++

前端 未结 7 498
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 06:16

I wrote the following code to check whether the input(answer3) is a number or string, if it is not a number it should return \"Enter Numbers Only\" but it returns the same e

7条回答
  •  轮回少年
    2020-12-10 06:52

    This is a somewhat old question, but I figured I'd add my own solution that I'm using in my code.

    Another way to check if a string is a number is the std::stod function, which has been mentioned, but I use it a bit differently. In my use case, I use a try-catch block to check if the input is a string or number, like so with your code:

    ...
    try {
        double n = stod(answer3);
        //This will only be reached if the number was converted properly.
        cout << "Correct" << endl;
    } catch (invalid_argument &ex) {
        cout << "Enter Numbers Only" << endl;
    }
    ...
    

    The primary problem with this solution is that strings that begin with numbers (but aren't all numbers) will be converted to numbers. This can be easily fixed by using std::to_string on the returned number and comparing it to the original string.

提交回复
热议问题