"when I input an Integer it returns the same value but when I input hello
it gives me 1961729588?
."
The cin >> N;
actually fails returning false
for the stream state, when a input is given that cannot be converted to an integer. You can check for such error condition with
if(!(cin >> N)) {
cerr << "Input a valid number!" << endl;
}
else {
cout << " The integer entered is:" << N << endl;
}
The value of N
will be initialized (reset) to int()
(default value) which actually renders to 0
.
Full live sample
#include <iostream>
using namespace std;
int main () {
int N;
cout << " Input an integer:";
if(!(cin >> N)) {
cout << "Input a valid number!" << endl;
cout << "N = " << N << endl;
}
else {
cout << " The integer entered is:" << N << endl;
}
return 0;
}
Input
Hello
Output
Input an integer:Input a valid number!
N = 0
This was cross checked with a Ideone code sample
I cannot reproduce getting some garbage value like 1961729588
. The value was correctly reset by the std::istream& operator>>(std::istream&, int&);
input operator.
Is it an issue of your current compiler's implementation, c++ standards level (-std=c++11
) settings?
I have found some notes about eventual differences regarding c++ standards at cppreference.com:


Though I didn't spot what they really refer to with 'a value as described above', to be honest.