从控制台读取字符串以及空格

Read string from console along with whitespaces

本文关键字:空格 字符串 控制台 读取      更新时间:2023-10-16

我想从cin中读取一个字符串,直到按下返回键。下面的代码出了什么问题?输出重复显示"发现无效响应,请再次输入:"即使我输入单个单词。。我已经更新了代码。。

int readInt() {
    int num;
    while (!(std::cin >> num)) {
        std::cout << "Invalid response found, please enter again: ";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    }
    return num;
}
string readString() {
    string str;
    while (std::getline(std::cin, str) && std::cin.fail()) {
        std::cout << "Invalid response found, please enter again: ";
        std::cin.clear();
        std::cin.ignore();
    }
    return str;
}
DVD_Node* addNewDvd(DVD_Node *head) {
    DVD_Node* temp = new DVD_Node;
    int new_id = getNewID(head);
    temp->id = new_id;
    cout << "nn-- Add a new DVD to your collection --";
    cout << "nnEnter movie name: ";
    temp->title = readString();
    cout << "nnEnter duration in minutes: ";
    temp->duration = readInt();
    cout << "nnEnter movie year: ";
    temp->year = readInt();
    cout << "nnEnter movie actor 1 name: ";
    temp->actor1 = readString();
    cout << "nnEnter movie actor 2 name: ";
    temp->actor2 = readString();
    temp->next = head;
    changes_remaining = 1;
    cout << "nnYour DVD Data has been added successfully.";
    return temp;
}

如果您想检测错误,下面的测试是不正确的:

std::getline(std::cin, str) && std::cin.fail()

事实上,因为getline返回输入,所以您希望检测空输入或错误:

std::getline(std::cin, str) == 0 || std::cin.fail()