跳过 cin 语句

cin statement being skipped

#include <iostream>
#include<string>
using namespace std;

int main()
{
    struct fruitType {
        int sugar;
        string name;
        string color;
        bool isSuperfood;
        string random;
};
    fruitType fruit;

    cout << "Enter the name of the fruit.";
    cin >> fruit.name;
    cout << endl << "What is the color of the fruit?";
    cin >> fruit.color;
    cout << endl << "Is it a superfood? Answer true or false.";
    cin >> fruit.isSuperfood;
    cout << endl << "How much sugar (in grams) does the fruit have?";
    cin >> fruit.sugar;
}

我的 fruit.sugar cin 函数不工作。当我 运行 程序时,它会跳过那个 cin 语句。我尝试在 cin 语句之前初始化糖,但得到了相同的结果。任何帮助都会有所帮助。

我的输入是“西瓜”、“绿色”和“真”。我无法为 sugar 语句输入任何内容。

问题出在这里:

cout << endl << "Is it a superfood? Answer true or false.";
cin >> fruit.isSuperfood;

isSuperfood 的类型是布尔值,您假设程序会接受字符串 "true""false",但实际上并非如此。相反,如果您输入 1,程序将理解 bool 为真,否则当输入 0.

时为假

在此处使用接受 "true""false""something" 等词的字符串,并编写一个仅接受 "true" 和 [=14] 的条件=]:

std::string isSuperFood;

// verifying if the input is valid
if (!(std::cin >> isSuperFood)) {
    std::cout << "Error!" << std::endl;
    return 1;
}

if (isSuperFood == "true" || isSuperFood == "false")
    std::cout << "OK";
else
    std::cout << "Not OK";

您可以说 true 对于 bool 持有 1,OTOH,false 持有 0