本文介绍了C ++检查数字是否为int/float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的.我在Google上找到了这个网站.
i'm new here. i found this site on google.
#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;
我需要类似的内容,当用户输入字母字符时,它会显示错误信息,提示您应该输入数字.
I need something like, when users enter alphabetical characters, it would display an error says, you should enter numbers.
任何帮助表示赞赏
推荐答案
首先,回答您的问题.这实际上非常容易,您不需要在代码中进行太多更改:
First, to answer your question. This is actually very easy and you don't need to change much in your code:
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;
}
此代码基本上检查输入是否被有效地解析为浮点数-如果未发生,则表示错误.
This code basically checks whether the input was validly parsed as a floating point number – if that didn't happen, it signals an error.
第二, main
始终的返回类型必须始终是 int
,而不是 void .
Secondly, the return type of
main
must always be int
, never void
.
这篇关于C ++检查数字是否为int/float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!