gpt4 book ai didi

c++ - 使用带有 cin 的 getline 指定用户输入

转载 作者:行者123 更新时间:2023-11-28 03:06:05 24 4
gpt4 key购买 nike

每当此函数中的输入类型出现错误时,它会自动将 *_cost 的值设置为 0。为什么会发生这种情况?

void Item::setCost(string input){
float entered;
istringstream stin;
stin.str(input);
if(!(stin >> entered)){
do{
cout << "invalid input" << endl;
stin.clear();
getline(cin, input);
stin.str(input);
*_cost = entered;
}
while(!(stin >> entered));
}
else{
*_cost = entered;
}
}

我在我的主要功能中使用该功能如下:

istringstream stin;
string input;

cout << "enter cost" << endl;
getline(cin, input);
items[i]->setCost(input);

最佳答案

您正在将 *_cost 设置为一个值,由于 if 语句,该值总是必然是不正确的值。
*_cost = entered 行只会在程序执行其“无效输入”代码时执行。该程序仅在输入的值不是合法值时打印“无效输入”。因此_cost只能设置为非法值。
要解决您的问题,请将 *_cost = entered 放在 do-while 循环之后。

我不确定您为什么不直接使用 std::cin 直接读取数据,而是将标准输入转换为 std::string 的实例,然后再转换为 istringstream。

关于c++ - 使用带有 cin 的 getline 指定用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19648986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com