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

时间:2014-10-11 22:15:20

标签: c++ cin getline

我想从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;
}

1 个答案:

答案 0 :(得分:0)

如果您想检测错误,以下测试不正确:

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

确实,因为 getline 返回输入,所以您希望使用 :

检测空输入或错误
std::getline(std::cin, str) == 0 || std::cin.fail()