C++ catching strings

I am making a very basic calculator, but the problem is that when I input a string, it goes on repeating itself infinitely.
Any help?
Instead of this:

std::cin >> x;

Use this:

1
2
3
4
5
6
while(!(std::cin >> x))
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits <std::streamsize> ::max(), '\n'); //see Duoas' post
    std::cout << "Try again: " << std::flush;
}
Last edited on
Just tried doesn't work, it keeps repeating itself:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
    int a = 0;

    while(!(std::cin >> a))
    {
        std::cin.clear();
        std::cout << "Try again: " << std::flush;
    }
}
Last edited on
You said you had a problem "when I input a string".
LB's code assumes x is a string.

But you are trying to input an integer. If it fails, you must also skip past the offending input.

The following will skip past everything the user typed before pressing Enter/Return and the newline itself before trying again.

1
2
3
4
5
6
7
8
    int a = 0;

    while (!(std::cin >> a))
    {
        std::cin.clear();
        std::cin.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );
        std::cout << "Try again: " << std::flush;
    }

Good luck!
Duoas wrote:
You said you had a problem "when I input a string".
LB's code assumes x is a string.
My code assumes x is a non-string, I just forgot to skip the bad input.
Last edited on
L B, I understand the process of clearing and ignoring cin, but what does flushing cout do?
@duoas
I am not declaring a string
I am inputting a string
I wrote "I am making a very basic calculator"
When those calculators take in strings? And if they do, it is not a simple one!

@trojan
flush means empty the previous input
for more http://www.cplusplus.com/reference/ostream/flush-free/
trojansdestroy wrote:
what does flushing cout do?
It ensures that what you put in std::cout gets written tot he target (e.g. forced to display on screen). std::cout is buffered, so when you write data to it, it might not actually send that data to the target - it could just stay in the buffer. std::endl calls std::flush as well.
@Donanza
Before you get too smarmy and bite the hand that's feeding you, why not try compiling and running the code I gave you?

It is really bad form to put-down the intelligence of someone trying to help when you don't really understand what you are doing to begin with.
I understand. Thank you. I didn't know std::endl called flush.

However, I've never had the problem of std::cout NOT writing to the target. Is this ever done intentionally? (I doubt so). If so, when, and why? If not so, what code would cause it not to write?
Normally cout is "tied" to cin. Whenever you use cin, cout is flushed automatically, so doing it in that case is superfluous.
Topic archived. No new replies allowed.