hey i am begginer and exploring all documentation. i encounter a very interesting thing.. in this piece of code if i trying to enter a character
or very big number the program just told me that i enter number (different number that i give)
and keep running it over and over... why its happens?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// number echoer
#include <iostream>
usingnamespace std;
int main ()
{
unsignedlong n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}
beacuse you are doing a cycle, which means that the programm will continue running until the condition is validated.
In your code you (or the from this random guy code) you are saying:
do this thing
1 2 3
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
If I understand this correctly, you entered a number bigger than what can fit in an unsigned long, and the program got stuck in an endless loop. This happened because you didn't test if the input operation (cin >>n in this case) succeeded. Always check if, for example, replace that line with
1 2 3 4
if (cin >> n)
cout << ...
elsebreak;
or rearrange the loop to make only one decision to continue
1 2 3 4
while( cout << "Enter..."
&& cin >> n
&& n != 0 )
cout << ...
But why the program keeps running i if i put value 21 all is good but if i put character
or very big number the program says that i put the number 3435973836 and keeps running it without asking me for another input whats the logic?
When you input a number that is bigger than what the specific data type can hold (in this case, unsigned long), the stream buffer cin goes into a fail state. Since it's in a fail state it cannot accept anymore input until it's state has been corrected.