首页 > 解决方案 > 如何让这个程序运行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;
}

标签: c++loops

解决方案


两件事情:

  1. 我们只运行了 4 次,所以应该是a < 4
  2. 拿到物品后,使用该std::getline功能。这将返回用户输入的所有内容,包括空格。
  3. 我们需要忽略空行。当我们再次开始循环时,有一个空行,因为用户在输入折扣后按了“回车”。所以我们需要将 放入getline一个循环中,并读取行,直到找到一个不为空的行。
  4. 当您在最后打印总成本时,添加一个换行符,这样当循环体再次开始时,我们就在一个新行上。

更新代码:

#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 使用数组,因为每次新的循环迭代都可以覆盖它们。


推荐阅读