Allow user to skip entering input and just pressin

2019-09-09 21:09发布

Is there any way I can allow the user to press only the Enter key without entering any input and proceed with the program in std::cin? Thanks!

_tprintf(_T("\nENTER CHOICE: "));
cin>>ch;
cin.ignore();

When I run the program with this code segment, chances are when I really don't want to enter anything on that field at all, when I press the enter key the cursor will just produce new lines.

标签: c++ input cin
3条回答
2楼-- · 2019-09-09 21:52

If I understood your question correctly, you can simply check if the input equals ""; if it doesn't, don't proceed with the requested action.

EDIT: Oh, now that you edited your question I figured out what you want. Just use cin.ignore();. You don't need to cin >> anything before that.

查看更多
We Are One
3楼-- · 2019-09-09 21:54

No, you cannot use cin to do that.

If you press the ENTER key when the program waits for an input, cin will completely ignore the newline (just like it ignores whitespaces due to skipws), store the newline character in the input stream and keep asking for an input. Unless it receives a valid input for the concerned type or encounters an EOF, it will keep asking you for an input.

Use the getline function instead.

#include <string>
...
cout << "Enter Something\n";
string a;
getline(cin, a);
查看更多
放我归山
4楼-- · 2019-09-09 21:56

if you "read in" std::noskipws, then reads will stop skipping whitespace. This means when you read in a single character, you can read in spaces and newlines and such.

#include <iostream>
#include <iomanip>

int main() {
    std::cin >> std::noskipws; //here's the magic
    char input;
    while(std::cin >> input) {
        std::cout << ">" << input << '\n';
    }
}

when run with the input:

a

b

c

produces:

>a
>

>

>b
>

>

>c

So we can see that it read in the letter a, then the enter key after the newline, then the empty line, then the letter b, etc.

If you want the user to hit the enter key after entering a number, you'll have to handle that in your code.

If the user is simply entering one "thing" per line, there's actually an easier way:

#include <iostream>

int main() {
     std::string line;
     while(std::getline(std::cin, line)) {
         std::cout << line << '\n';
     }
}

This will read the characters from the input until the end of the line, allowing you to read lines with spaces, or lines with nothing at all. Be warned that after you use std::cin >> it commonly leaves the newline key in the input, so if you do a std::getline right after it will return an empty string. To avoid this, you can use std::cin.ignore(1, '\n') to make it ignore the newline before you try to use std::getline.

查看更多
登录 后发表回答