我如何告诉 cin 不允许输入空格? (C++)
How do I tell cin to not allow spaces on input? (C++)
运行时我不想在 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";
}
如果用户在字符串之前输入空格,将会出错,因为无法成功读取任何单词。
运行时我不想在 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";
}
如果用户在字符串之前输入空格,将会出错,因为无法成功读取任何单词。