Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hellow every one...
I have a C/C++ program. And when i run this code the behavior of program is very odd.

What I have tried:

C++
#include "stdafx.h"
#include "iostream"
using namespace std;

int main() {
	int n;

	do {
		cout << "Enter a number   = ";
		cin >> n;
	} while (n != 2);
}



Compile This code is and enter a integer value except 2 the code works well.
Now enter a character or a float (not integer) number and see the odd behavior.
No matter you use for, while or do-while loop the behavior is the same.
I tried this code in visual studio 2012, 2013, 2015 and turbo C 3.1 versions. The behavior is same.

So can any one help me in to solve this problem.
Posted
Updated 22-Jun-18 21:05pm
Comments
[no name] 23-Jun-18 2:56am    
In a technical forum you should tell us the behaviour you expect and observe. This is not a guessing contest. So what is the problem exactly? You have declared n an int so enter a float and the result will of course be unpredictable. Google will explain it all.
Richard MacCutchan 23-Jun-18 3:47am    
Your program asks for a number, so it should check that only a number has been entered. Programming is not just about writing the logic, it is also about validating the inputs provided by users.

1 solution

The short answer is that, on detecting invalid input, cin (which is an istream) sets its fail status bit, causing further input to be ignored until the stream's error is cleared. This is not unexpected at all. It's been part of the standard behaviour since forever.
 
Share this answer
 
Comments
[no name] 23-Jun-18 3:33am    
It fails, that is certainly predictable but in this case what is the value of n?
Jochen Arndt 23-Jun-18 3:50am    
See https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt:

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set. (until C++11)

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits<t>::max() or std::numeric_limits<t>::min() is written and failbit flag is set. (since C++11)
Peter_in_2780 23-Jun-18 4:01am    
Thank you! I knew about failbit, but I didn't know about returning zero since C++11. Want to make it a solution? (then I can upvote it :p )
Jochen Arndt 23-Jun-18 12:58pm    
Thank you. But I don't think that it is necessary to put this into a solution. You described already what is happening. In such error cases the value itself does not really matter (besides that it can be used to detect out of range inputs with C++11).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900