允许用户跳过输入内容,只需按Enter键 [英] Allow user to skip entering input and just pressing Enter key

查看:87
本文介绍了允许用户跳过输入内容,只需按Enter键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以允许用户仅按Enter键而不输入任何内容,然后继续执行 std :: cin 中的程序?谢谢!

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();

当我使用此代码段运行程序时,很可能是我真的不想输入该字段上的所有内容,当我按Enter键时,光标只会产生新行。

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.

推荐答案

如果您读 std :: noskipws ,则读取将停止跳过空白。

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';
    }
}

当运行以下输入时:

a

b

c

产生:

>a
>

>

>b
>

>

>c

所以我们可以看到它在信中读到 a ,然后在换行符之后输入Enter键,然后在空行中输入字母 b ,等等。

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.

如果您希望用户在输入数字后按Enter键,则必须在代码中进行处理。

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';
     }
}

这将从输入中读取字符直到结尾的行,使您可以读取带有空格的行或根本不包含任何行的行。请注意,在使用 std :: cin>> 后,通常会将换行键留在输入中,因此,如果执行 std: :getline 之后,它将返回一个空字符串。为避免这种情况,可以在尝试使用<$ c $之前使用 std :: cin.ignore(1,'\n')使其忽略换行符。 c> std :: getline 。

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.

这篇关于允许用户跳过输入内容,只需按Enter键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆