我如何告诉cin不允许输入空格?(c++)

How do I tell cin to not allow spaces on input? (C++)

本文关键字:c++ 空格 输入 何告诉 cin 不允许      更新时间:2023-10-16

当这运行时,我想不能在cin中输入任何空格,我可以为此使用什么格式说明符?

<string>中有什么东西可以让我这样做吗?

#include <iostream>
#include <string>
using namespace std;
int main(){
    string yy;
    cin >> string;
    /*when this runs I want to not be able to enter any spaces in `cin`
    what format specifier can I use for this? is their anything in      `<string>` that lets me do this?
    */
    return 0;
}

您可以使用std::noskipws来禁用在格式化输入之前自动跳过空白:

if (std::cin >> std::noskipws >> yy) {
    std::cout << "read '" << yy << "'n";
}

如果用户在字符串之前输入空格,则会出现错误,因为没有单词可以成功读取。