[英]C++ keyboard input into 2 arrays
我想弄清楚以下几点:假设我们要求用户输入多行(每行有 2 个值,一个是字符串,另一个是数字;例如:'milk 2.55' 'juice 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
或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;
}
不要使用过时的数组。 使用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个杂货店名称。
我假设如果他在做数组,那是因为那是任务。 为什么人们不能回答人们提出的问题? 如果你没有答案就忽略它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.