C++ 从控制台读取字符串和空格

C++ 从控制台读取字符串和空格,c++,cin,getline,C++,Cin,Getline,我想从cin读取字符串,直到按下返回键。以下代码有什么问题?输出重复地说“找到无效响应,请再次输入:”即使我输入单个单词。。我已经更新了代码 int readInt() { int num; while (!(std::cin >> num)) { std::cout << "Invalid response found, please enter again: "; std::cin.clear(); st

我想从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 << "\n\n-- Add a new DVD to your collection --";
    cout << "\n\nEnter movie name: ";
    temp->title = readString();

    cout << "\n\nEnter duration in minutes: ";
    temp->duration = readInt();

    cout << "\n\nEnter movie year: ";
    temp->year = readInt();

    cout << "\n\nEnter movie actor 1 name: ";
    temp->actor1 = readString();

    cout << "\n\nEnter movie actor 2 name: ";
    temp->actor2 = readString();

    temp->next = head;

    changes_remaining = 1;
    cout << "\n\nYour DVD Data has been added successfully.";

    return temp;
}
int readInt(){
int-num;
而(!(std::cin>>num)){

std::cout不应该是
std::getline(std::cin,str)和&std::cin.fail()
?您对“无效响应”的定义是什么?在编写代码之前,确保您理解您试图解决的问题。
getline
无论如何都会返回流,失败检查是多余的,您应该检查
!std::getline(std::cin,str)
请查看更新后的代码。当我运行它并输入数据时,我得到temp->title=“”,temp->duration,temp->years,temp->actor1=“”和temp->actor2=…
std::getline(std::cin,str)和&std::cin.fail()
患有精神分裂症。如果读取没有失败,前半部分转换为
true
;如果读取失败,后半部分转换为
true