【问题标题】:Read string from console along with whitespaces从控制台读取字符串以及空格
【发布时间】:2014-12-06 19:50:59
【问题描述】:

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

【问题讨论】:

  • 不应该是std::getline(std::cin, str) &amp;&amp; std::cin.fail()吗?
  • 您对“无效响应”的定义是什么?在编写代码之前,请确保您了解要解决的问题。
  • getline 无论如何都会返回流,失败检查是多余的,你应该检查!std::getline(std::cin, str)
  • std::getline(std::cin, str) &amp;&amp; std::cin.fail() 患有精神分裂症。如果读取没有失败,前半部分将转换为true;后半部分是true,如果它确实失败了。
  • @T.C.我已将其更改为 while (!std::getline(std::cin, str) || std::cin.fail())

标签: c++ cin getline


【解决方案1】:

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

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

确实,因为getline 返回输入,您想要检测空输入或错误:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2013-11-20
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多