处理空格字符作为输入

时间:2015-09-28 18:48:15

标签: c++ cin

#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。如何克服这个问题呢?

2 个答案:

答案 0 :(得分:0)

我会一次读取一行到缓冲区并使用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是我测试过的示例输入。

答案 1 :(得分:0)

我找到了解决方案。 std::noskipws表示不要跳过空格。

#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 >> noskipws >> y;
    while (!(!isblank(y) && isalpha(y)))
    {
        cout << "You have entered wrong values try again!" << endl;
        cout << "Enter x and y again => ";
        cin.clear();
        cin.ignore(256,'\n');
        cin >> x >> y;
    }
    return 0;
}