[英]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 function 不工作。 当我运行该程序时,它会跳过该 cin 语句。 我尝试在 cin 语句之前初始化糖,但得到了相同的结果。 任何帮助都会有所帮助。
我的输入是“西瓜”、“绿色”和“真实”。 我无法为糖声明输入任何内容。
问题在这里:
cout << endl << "Is it a superfood? Answer true or false.";
cin >> fruit.isSuperfood;
isSuperfood 的类型是isSuperfood
并且您的假设是程序将接受字符串"true"
和"false"
,但实际上并非如此。 相反,如果您输入1
,程序将理解bool
为 true ,否则输入0
时为 false 。
在此处使用接受诸如"true"
、 "false"
、 "something"
等词的字符串,并编写一个仅接受"true"
和"false"
的条件:
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
for bool
持有1
, OTOH, false
持有0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.