c++ - 如何让这个程序运行4次没有结束
问题描述
我这学期刚开始“C++ 简介”,我一直在做一个练习,该练习涉及从表格中获取数据并编写一个程序,让您输入和显示每个项目(逐行)显示项目、成本、并计算总成本。
我编写的程序非常适合第一个项目,但我需要它重复相同的 3 个问题(允许用户在每次重复问题时输入不同的项目/成本/折扣),同时在每个问题后打印计算的总数被回答。我假设这将涉及do-while
循环或for
循环,但我无法弄清楚如何将我已经编写的内容集成到循环中。
#include <iostream>
using namespace std;
int main()
{
string Item;
float Cost;
float Discount;
float TotalCost;
cout << "What is the item? \n";
cin >> Item;
cout << "What is the cost? \n";
cin >> Cost;
cout << "What is the discount? \n";
cin >> Discount;
TotalCost = Cost - Discount;
cout << Item << "'s Total Cost is " << TotalCost;
return 0;
}
我尝试过创建一个for
循环(我在下面尝试过的代码),但它不起作用,而且我无法在我的书中或在线找到任何涉及每次流程循环时接受用户输入的循环示例.
#include <iostream>
using namespace std;
int main()
{
string Item;
float Cost;
float Discount;
float TotalCost;
for (int a = 0; a < 5; a++)
{
cout << "What is the item? \n";
cin >> Item;
cout << "What is the cost? \n";
cin >> Cost;
cout << "What is the discount? \n";
cin >> Discount;
TotalCost = Cost - Discount;
cout << Item << "'s Total Cost is " << TotalCost;
}
return 0;
}
解决方案
两件事情:
- 我们只运行了 4 次,所以应该是
a < 4
- 拿到物品后,使用该
std::getline
功能。这将返回用户输入的所有内容,包括空格。 - 我们需要忽略空行。当我们再次开始循环时,有一个空行,因为用户在输入折扣后按了“回车”。所以我们需要将 放入
getline
一个循环中,并读取行,直到找到一个不为空的行。 - 当您在最后打印总成本时,添加一个换行符,这样当循环体再次开始时,我们就在一个新行上。
更新代码:
#include <iostream>
using namespace std;
int main()
{
string Item;
float Cost;
float Discount;
float TotalCost;
for (int a = 0; a < 4; a++) // (1)
{
cout << "What is the item? \n";
do {
// (2) Use the std::getline function to get the entire line.
std::getline(std::cin, Item);
// (3) Empty lines should be ignored. If the line is empty,
// Get a line again.
} while(Item.size() == 0);
cout << "What is the cost? \n";
cin >> Cost;
cout << "What is the discount? \n";
cin >> Discount;
TotalCost = Cost - Discount;
// (4) Put a newline here at the end to make sure the buffer
// Gets flushed before the loop starts again.
cout << Item << "'s Total Cost is " << TotalCost << '\n';
}
return 0;
}
您不需要为 Cost、Discount 或 TotalCost 使用数组,因为每次新的循环迭代都可以覆盖它们。
推荐阅读
- java - 在 android/java Activity 之间切换和传递数据
- javascript - React 表单在单击时立即失去焦点并滚动页面
- c# - 使用某些 String.IndexOf 覆盖时构建失败
- c# - 在其他字符串数组中查找字符串数组
- go - 从 go-chi 路由处理程序访问数据库实例
- git - 显示导致两个提交之间差异的提交
- javascript - 如何在变量中使用 Xpath 来提取数据?
- java - Java字符串array.contains(具有相同属性名称的对象)
- flutter - 在颤振中添加 mlkit 会增加应用程序大小
- c++ - QT 从布局中检索自定义小部件