How can i check if the user didn't input anything and just hit enter?

Is there a way to make cin NOT wait for an input?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int main ()
{
    int choice;

    cout << "This program translates integers with magnitudes less than a billion into words" << "\n";
    cout << "Enter 0 to terminate" << "\n";
    cout << "\n";


    do
    {
    cout << "Enter a number: ";
    cin >> choice;                  //how can i check if the user just hit enter?
    cout << choice << "\n";

    if (choice != 0)
    {
       Numbers object1(choice);
    }



    } while (choice != 0);


}
Last edited on
Wen ever you hot enter this should be a new line left in buffer you could check if that is in buffer
So should I just use cin.ignore ()? Are there any other functions that check the buffer?
You can use cin.get to grab a character from the buffer, and if that character is a new line then you will know they did not enter anything.
Hmm i tried the cin.get function but the thing is, it is not forcing cin to stop waiting for an input. Is there a function that forces cin to stop reading even though there is no input?
Last edited on
If you use std::getline, you will get an empty string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::cout << "Enter something: ";
std::string line;
if(std::getline(std::cin, line))
{
    if(line == "") //alternative form: if(line.empty())
    {
        std::cout << "You pressed enter without typing anything" << std::endl;
    }
    else
    {
        std::cout << "Thanks!" << std::endl;
    }
}
else
{
    std::cout << "Input failed - no more input?" << std::endl;
}
To get the "Input failed" output, you can press Ctrl+Z and then Enter in a Windows console - this terminates program input (e.g. you can never, ever read input ever again).
Last edited on
Yes but i thought std::getline only works with char or string type variables, if i use an int with getline it wont seem to work.

I even tried using std::stringstream to later convert a string to an int but there seems to be bugs when i pass the converted int variable to a member function
Typically you should always read entire lines of input at a time and then use std::istringstream to extract the information you want.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    const char newline = '\n' ;

    std::cout << "enter an integer (or just enter to quit): " ;
    int a ;
    if( std::cin.peek() != newline && std::cin >> a )
    {
        std::cin.ignore( 1000000, '\n' ) ; // extract and throw away the new line

        std::cout << "enter another integer (or just enter to quit): " ;
        int b ;
        if( std::cin.peek() != newline && std::cin >> b )
            std::cout << a << " + " << b  << " == " << a+b << '\n' ;
    }
}
Topic archived. No new replies allowed.