【问题标题】:Error checking two separate inputs检查两个单独的输入时出错
【发布时间】: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&gt;&gt;
  • 并退出 using namespace std.. 原因? Here
  • @amanuel2 尽管有其他帖子,在这种特殊情况下实际上没有理由不使用整个命名空间。
  • @JasonC 当然你对这个案子的权利。但是当他做更大的项目时,这种不良做法可能会卷土重来。最好避免它;)
  • @amanuel2 @JasonC 感谢您在这种情况下是否使用命名空间 std 的意见。我理解为什么这不是一个好习惯,但我的教授说暂时最好使用它,因为我们只是在学习 C++ 编码的基础知识。

标签: c++ function get stream cin


【解决方案1】:

你可以一直使用&gt;&gt;int,删除所有get() 的东西和字符处理,然后检查cin.fail()。例如(我将把它留在你的程序中,并在循环中重复它作为你的练习):

int x;
cin >> x;
if (cin.fail())
    cout << "Not a valid integer." << endl;

您可以以完全相同的方式处理所有后续输入。没有理由只将operator &gt;&gt; 限制为第一个输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    相关资源
    最近更新 更多