c++键盘输入成2个数组

C++ keyboard input into 2 arrays

本文关键字:2个 数组 输入 键盘 c++      更新时间:2023-10-16

我想弄清楚以下内容:假设我们要求用户输入多行(每行有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::pairstd::tuplestruct这样的简单对象的单个向量中。这样,您就不需要维护两个不同的数据集合,并且可以根据需要添加任意多的项。使用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;
}

你可以看到这个运行的例子

不要使用数组,它太过时了。使用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;
}

那么您可以简单地执行names[49]来获得第50个杂货店名称。