c++键盘输入成2个数组
C++ keyboard input into 2 arrays
我想弄清楚以下内容:假设我们要求用户输入多行(每行有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
或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个杂货店名称。
相关文章:
- 如何在C++中比较两个char数组
- 在c++中获取两个大int,并将它们存储在数组中
- 如何以优化的方式同时迭代两个间距不相等的数组
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 如何从txt文件中读取多个不同长度的数组?
- C++,数组有多少个地址?
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 为什么 2 个相同数组的元素彼此相等
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 可以将两个相同类型的连续数组视为一个数组吗?
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- C++递归来决定数组中的两个值
- 具有 2 个分量的数组的特征映射到 3 的向量
- C++ 2D 数组写入多个位置
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- C++:在多个线程中访问同一数组/向量的不同单元格是否会产生数据竞赛?
- VTK 图像数据,访问数组中的 1 个图像
- 需要使用模板查找数组的第二个最小和最小值