C++键盘输入到2个数组

标签 c++

我正在尝试弄清楚以下内容: 假设我们要求用户输入多行(每行有 2 个值,一个是字符串,另一个是数字;示例: '牛奶 2.55' '果汁 3.15')。 现在我如何运行一个循环来读取所有行并分配给两个不同的数组(字符串输入到字符串数组和数字到双数组)。两个数组的值都设置为 50 (array[50]),我不知道用户将输入多少行。如果我运行一个 for 循环并设置...i<50...它将填充两个数组最多 50 个值(如果我们只考虑输入 2 行,每个数组将添加 2 个正确值和 48 个“垃圾”值) . 我希望能够读取一行,将每个值分配给适当的数组并计算添加了多少个值。

如果我知道会有多少行(比如说 3 行)就可以正常工作

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

int main()
{
    string itemnames[50]; 
    double itemprices[50]; 
    double subtotal = 0, tax, total;
    const double TAX_RATE = 0.095;
    int count = 0;



    cout << "\nPlease enter the names and prices of the items you wish "
        << "to purchase:\n";



    for (int i = 1; i <= 50; i++){
        cin >> itemnames[i] >> itemprices[i];
    }



    for (int i = 1; i <= 3; i++){

            subtotal += itemprices[i];

    }


    tax = subtotal * TAX_RATE;
    total = subtotal + tax;

    cout << endl;


    cout << left << setw(10) << "item"
        << right << setw(10) << "price" << endl
        << "--------------------" << endl;

    for (int j = 1; j <=3; j++){
        cout << setprecision(2) << fixed
            << left << setw(10) << itemnames[j]
            << right << setw(10) << itemprices[j] << endl;
    }

        cout<< "--------------------" << endl

        << left << setw(10) << "subtotal"
        << right << setw(10) << subtotal << endl << endl

        << left << setw(10) << "tax"
        << right << setw(10) << tax << endl

        << left << setw(10) << "total"
        << right << setw(10) << total << endl << endl;

    return 0;
}

最佳答案

执行此操作的最简单方法是将元素插入到 std::pair 的单个 vector 中或 std::tuple或者像 struct 这样的简单对象。这样你就不需要维护两个不同的数据集合,并且你可以根据需要添加任意数量的项目。使用 struct 它看起来像:

struct Item
{
    std::string name;
    double price;
};

std::istream & operator >>(std::istream & is, Item & item)
{
    is >> item.name >> item.price;
    return is;
}

int main ()
{
    std::vector<Item> items;
    Item reader;
    // get items
    while (cin >> reader)
        items.push_back(reader);

    // display items
    for (const auto & e : items)
        std::cout << e.name << "\t" << e.price << std::endl;

    return 0;
}

您可以看到使用此 Live Example 运行的示例

关于C++键盘输入到2个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31889081/

相关文章:

c++ - 我的选择排序代码是否存在导致它跳过数组中的元素的问题?

c++ - VC++编译器和类型转换?

c++ - 在 Windows 中使用 C++ 截取窗口截图的最佳方法是什么?

c++ - 没有定义的类函数如何不导致错误

c++ - vector 中的指针

c++ - Constexpr 可构造函数对象

c++ - Clang 格式的换行符

c++ - 链接错误 LNK1120 和 LNK2019 - "unresolved external symbol _main"

c++ - sqlite3_step() 有什么问题?

c++ - AllocaInst 的使用示例 : LLVM