繁体   English   中英

输入字符串时跳过cin?

[英]Skipped cin when a string is entered?

我是C ++的新手,我正在试验C ++中的函数是如何工作的。

#include <iostream>

using namespace std;

int add(int num, int num2){
    return num + num2;
}

int main(){

    int n1, n2;
    cout << "first\t";
    cin >> n1;
    cout << "second\t";
    cin >> n2;

    cout << "----------\nResult\t" << add(n1, n2) << endl << endl;

    return 0;
}

输入两个数字时效果很好; 但是当我输入一个字符串时,它只是跳过cin >> n2行并返回6959982

first   test
second  ----------
Result  6959982

为什么会这样?

什么都没读。 Stream获取失败位并忽略所有后续读数。

6959982 is initial value of n2.

你应该检查阅读的结果。 例:

if(!(cin >> n1)) {
   cout << "input is garbage!";
}

http://www.parashift.com/c++-faq/istream-and-ignore.html

// Ask for a number, and if it is not a number, report invalid input.
while ((std::cout << "Number: ") && !(std::cin >> num)) {
    std::cout << "Invalid Input." << std::endl;
}

有趣的数字是因为在C ++中,整数默认不是0(它们可以取决于实现)。 因此,无论何时声明数字,都应将其设置为默认值:

int x = 0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM