Why cin inside while doesn't stop to get user input? - c++

I'm starting now with C++, so I imagine this is gonna be a very easy-newbie question.
Well, why the "cin >> x" line inside while doesn't stop the loop to get the user input (if the user inputs a character, in place of a number)?
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int x = 0;
cout << "Please, enter x: ";
cin >> x;
while (!cin)
{
cout << "Please, it must be a number!\n";
cin >> x;
}
cout << "Thanks!.";
cin.ignore();
cin.ignore();
}
I'm barely two days studiying C++, so I'm completely blind about what "cin" really is. I tried with "cin.sync()" and "cin.clear()", but still no luck.
And I know it is impossible to do something like "cin=true", or "cout << cin".

Well, your program should be corrected slightly
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int x = 0;
cout << "Please, enter x: ";
cin >> x;
while (!cin)
{
cin.clear();
cin.ignore(10000, '\n');
cout << "Please, it must be a number!" << endl;
cin >> x;
}
cout << "Thanks!.";
}
This way it works as expected. More info about it here. In general, you need to clear all the errorneous stuff from cin.

if user input a character than it will take the ascii value of character so it will not stop.
To stop the loop enter 0.

Related

Making the user give a boolean input with while loop

I have just started learning C++ and trying to learn the syntax.
#include <iostream>
#include <limits>
using namespace std;
int main(){
bool answer;
cout << "Did you enjoy testing this program? (1 for yes, 0 for no) ";
cin >> answer;
while (!(cin >> answer)) {
cout << "Invalid value!\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please type either 0 or 1: ";
cin >> answer;
}
cout << "Your feedback has been registered. Feedback: " << answer;
}
The aim is to keep making the user ask over and over until they input either 0 or 1. The code snippet just makes things freeze when either of those values is given. How should this be fixed?
The cin >> answer; statement above the loop, and the cin >> answer; statement at the end of the loop body, both need to be removed.
You are prompting the user to enter a value, then you read in that value and ignore it, and then you wait for the user to enter in another value, even though you didn't prompt the user to enter more than 1 value.
If they do happen to enter a 2nd value, and it fails, your loop will then prompt the user to enter in a new value, then you read in that value and ignore it, and then you wait for the user to enter yet another value without prompting the user to do so.
You should be invoking cin >> answer only 1 time per loop iteration, eg:
#include <iostream>
#include <limits>
using namespace std;
int main(){
bool answer;
cout << "Did you enjoy testing this program? (1 for yes, 0 for no) ";
// cin >> answer; // <- remove this!
while (!(cin >> answer)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid value!\n";
cout << "Please type either 0 or 1: ";
// cin >> answer; // <- remove this!
}
cout << "Your feedback has been registered. Feedback: " << answer;
}

How to get a blank line after cin

I need a line to separate the users inputs from the results. This is for a basic computer science course.
cout << "Please enter (variable): ";
cin >> (variable);
cout << "\n\n:";
cout << "(results)" << endl;
Is there any other way to get the blank line after the cin, or is this viable code?
You can use endl rather than the \n if you want, but what you have is fine.
What you have is ok. However, this is another, more compact and legible option:
out << "Please enter (variable): ";
cin >> (variable);
cout << endl << "(results)" << endl;
Although the question is old and answered, but the given answers have some pitfalls according to the official GNU documentation.
endl is mistakenly used for newline by many coders, which is not what it is made for, and using it for this purpose renders it less efficient for it's true use case. It is used for flushing the buffers, using it very often for just newlines would make you prone to use it while you are writing text/data in a file and that use would be effecting it's buffering efficiency.
Morever flushing buffer each time you need a newline is not a desireable thing.
So how can you add new-line whenever you use cin
If variable is string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string var;
cout << "Please enter (variable):\n";
getline(cin, var);
cout << "(results)" << var << "\n";
return 0;
}
If variable is not string
cout << "Please enter (variable):\n";
cin >> (variable);
cout << "\n(results)\n";
#include <iostream>
using namespace std;
int main ()
{
int a, b;
cout << "Give 'a' a value: ";
cin >> a;
cout << "" << endl;
cout << "Give 'b' a value: ";
cin >> b;
cout << "" << endl;
return 0;
}

C++ Check if input is float using only #iostream

I would like to validate if the user input is Float or not, the program checks if the input was float and prints "Number is fine" else it prints "Number is not fine" and it continue the loop without taking the failed attempt in consideration of the loop, in other way it gives him another try to enter a float number instead.
The problem is that the program goes on infinity loop once the user enter a "Character". what i actually want it to do is just printing "Number isn't fine" then continue.
Can anybody tell me why does this happen, also please consider not to use any additional libraries.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int x;
float num;
cout << "Please enter the amount of numbers you wish to enter" << endl;
cin >> x;
cout << "Please enter the numbers" << endl;
for(int i=0; i < x;) {
if(!(cin >> num)) {
cout << "Number isn't fine" << endl;
continue;
}
cout << "Number is fine" << endl;
++i;
}
system("pause");
}
#Steve your solution worked by using both cin.clear() and cin.ignore
#AndyG Thanks for your help but unfortunately im limited to the simplest way.
Here is the final code if somebody wanted to know how it looks in the future.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int x;
float num;
cout << "Please enter the size of numbers" << endl;
cin >> x;
cout << "Please enter the numbers" << endl;
for(int i=0; i < x;) {
if(!(cin >> num)) {
cin.clear();
cin.ignore();
cout << "not a float number" << endl;
continue;
}
cout << "Number is fine" << endl;
++i;
}
system("pause");
}
If cin >> num fails to read a number then the stream is put into the failed state (that is, the failbit is set), and it doesn't read past the character that caused it to fail. You never do anything to clear() the fail state or to ignore() the bad data, so you loop forever.

Can't get char from cin.get()

I'm working through some beginner exercises on c++, and this has me stumped. I can enter a number, but I don't get the option to enter a character afterwards, and it skips to the final line.
I know I can use cin >> symbol, but i would like to know why this isn't working.
#include<iostream>
using namespace std;
int main() {
cout << "Enter a number:\n";
int number;
cin >> number;
char symbol;
cout << "Enter a letter:\n";
cin.get(symbol);
cout << number << " " << symbol << endl;
return 0;
}
You should remove '\n' from stream, remained after entering the number:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Without it you will read newline character. You could check that with:
std::cout << (symbol == '\n') << std::endl;
\n will remain in the buffer after the first cin. You can solve this problem by adding an empty cin.get() between two consecutive reads.
cin.get(string1,maxsize);
cin.get();
cin.get(string2,maxsize);
Or you can use fflush:
cin.get(string1,maxsize);
fflush(stdin);
cin.get(string2,maxsize);

Cin.clear() issue

Im writing a program that is supposed to accept integers only, I'm currently using
int x;
cin >> x;
while(cin.fail()){
cout << "error, please enter an integer" << endl;
cin.clear();
cin.ignore();
cin >> z;
cout << "you entered" << z << endl;
}
however if i enter a double for example 1.2 the program ignores the decimal point but sets the value of z to 2 and doesnt request user input.
What can i do to stop this?
Before this goes out of hand, here's once again a typical example of an input operation:
#include <string> // for std::getline
#include <iostream> // for std::cin
#include <sstream> // for std::istringstream
for (std::string line; std::cout << "Please enter an integer:" &&
std::getline(std::cin, line); )
{
int n;
std::istringstream iss(line);
if (!(iss >> n >> std::ws) || iss.get() != EOF)
{
std::cout << "Sorry, that did not make sense. Try again.\n";
}
else
{
std::cout << "Thank you. You said " << n << ".\n";
}
}
It will keep asking you for integers until you close the input stream or terminate it in some other way (e.g. by typing Ctrl-D).
You will find hundreds, if not thousands, of variations on this theme on this website.