C++检查数字是否为int/float

8 c++

我是新来的.我在谷歌上发现了这个网站.

#include <iostream>

using namespace std;

void main() {

    // Declaration of Variable
    float num1=0.0,num2=0.0;

    // Getting information from users for number 1
    cout << "Please enter x-axis coordinate location : ";
    cin >> num1;

    // Getting information from users for number 2
    cout << "Please enter y-axis coordinate location : ";
    cin >> num2;

    cout << "You enter number 1 : " << num1 << " and number 2 : " << num2 <<endl;
Run Code Online (Sandbox Code Playgroud)

我需要一些类似的东西,当用户输入字母字符时,会显示一个错误,你应该输入数字.

任何帮助非常感谢

Kon*_*lph 18

首先,回答你的问题.这实际上非常简单,您不需要在代码中进行太多更改:

cout << "Please enter x-axis coordinate location : " << flush;
if (!(cin >> num1)) {
    cout << "You did not enter a correct number!" << endl;
    // Leave the program, or do something appropriate:
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

此代码基本上检查输入是否被有效地解析为浮点数 - 如果没有发生,则表示错误.

其次,返回类型main 必须 始终int,永远不会void.


pio*_*otr 7

我使用cin.fail()方法或Boost"lexical cast",使用异常来捕获错误http://www.boost.org/doc/libs/1_38_0/libs/conversion/lexical_cast.htm


Bla*_*jac 6

使用类似的东西

if (static_cast<int>(num1) == num1) {
  // int value
}
else {
  // non-integer value
}
Run Code Online (Sandbox Code Playgroud)