C ++键盘输入2个数组

时间:2015-08-08 02:38:52

标签: c++

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

如果我知道将会有多少行(例如让我们说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;
}

2 个答案:

答案 0 :(得分:1)

最简单的方法是将元素插入std::pairstd::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

查看此示例

答案 1 :(得分:0)

不要使用阵列,它太老式了。使用../../b简单。

vector

然后你可以简单地#include<iostream> #include<vector> using namespace std; int main(){ vector<float> costs; vector<string> names; char choice = 'y'; while(choice != y){ float price; cout<<"Enter price: "; cin>>price; costs.push_back(price); string name; cout<<"Enter grocery name: "; cin>>name; names.push_back(name); cout<<"Enter y to continue"; cin>>choice; } return 0; } 来获得第50个杂货店名称。