gpt4 book ai didi

c++ - 处理空格字符作为输入

转载 作者:太空宇宙 更新时间:2023-11-04 13:27:31 24 4
gpt4 key购买 nike

#include <iostream>
using namespace std;

int main() {
int x;
char y;
cin >> x;
while(!cin)
{
cout << "Error" << endl;
cout << "Enter x and y again => ";
cin.clear();
cin.ignore(256,'\n');
cin >> x;
}
cin >> y;
while (!(!isblank(y) && isalpha(y)))
{
cout << "You have entered wrong values try again!" << endl;
cout << "Enter x and y again => ";
cin >> x >> y;
}
return 0;
}

如果输入的输入是 1 a,我会尝试处理。 x 应该是一个数字 y 也应该是字母字符。它应该再次要求输入值 xy。然而,事实并非如此。它应该接受 1a。如何克服这个问题?

最佳答案

我会一次读取一行到缓冲区中,然后使用 stringstream 从该缓冲区中读取。这是对我有用的:

int x;
char y;
bool readin_successful = false;
while (cin) {
cout << "Please enter x and y => ";
char z;
string buffer;
getline(cin, buffer);
stringstream bin(buffer);
bin >> x >> y;
bool const first_ok = (isalpha(y) and bin.good());
bin >> z;
if (first_ok and not bin.good()) {
readin_successful = true;
break;
}
cout << "You have entered wrong values try again!" << endl;
}
cout << "Read: " << x << " " << y << " " << readin_successful << endl;

它接受 0 x0x,但不接受任何其他内容(忽略空格)。 Here是我测试过的示例输入。

关于c++ - 处理空格字符作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32829809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com