Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

Skipped cin when a string is entered?

I'm new to C++, and I am experimenting on how functions in C++ work.

#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;
}

It works great when I enter two numbers; but when I enter a string, it simply skipped the cin >> n2 line and return 6959982.

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

Why is that happening?

Upvotes: 0

Views: 89

Answers (2)

RiaD
RiaD

Reputation: 47620

Just nothing is read. Stream gets the fail bit and ignores all subsequent readings.

6959982 is initial value of n2.

You should check the result of reading. Example:

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

Upvotes: 2

scaryrawr
scaryrawr

Reputation: 867

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;
}

The funny number is because in C++, integers are by default not 0 (they can be depending on the implementation). So whenever you declare a number, you should set it to a default:

int x = 0;

Upvotes: 0

Related Questions