【发布时间】:2017-02-07 04:09:31
【问题描述】:
我正在尝试检查两个单独的输入是否为整数。我可以对一个输入进行错误检查,但如果我使用“get”函数并且两个输入都来自“cin”流,我不太确定如何检查两个单独的输入。使用 c++。
我检查一个整数的代码如下所示。
#include <iostream>
using namespace std;
int main() {
int input;
cout << "Enter an integer: ";
cin >> input;
char next;
int x=0;
int done = 0;
while (!done){
next = cin.get();
if (next == ' ' || next == '\n'){
cout << "The Integer that you have entered is: " << input << "\n";
done = 1;
}
else if (next == '.'){
cerr << "Error: Invalid Input. Not an Integer." << "\n";
done = 1;
}
else{
cerr << "Error: Invalid Input. Not a number." << "\n";
done = 1;
}
}
return 0;
}
【问题讨论】:
-
使用
std::getline而不是operator>>。 -
并退出 using namespace std.. 原因? Here
-
@amanuel2 尽管有其他帖子,在这种特殊情况下实际上没有理由不使用整个命名空间。
-
@JasonC 当然你对这个案子的权利。但是当他做更大的项目时,这种不良做法可能会卷土重来。最好避免它;)
-
@amanuel2 @JasonC 感谢您在这种情况下是否使用命名空间 std 的意见。我理解为什么这不是一个好习惯,但我的教授说暂时最好使用它,因为我们只是在学习 C++ 编码的基础知识。
标签: c++ function get stream cin