将两个矢量并排打印到屏幕上
Printing two vectors to screen in columns next to each other?
因此,我的程序使用while循环来填充两个单独的向量,方法是询问项目的名称(向量一),然后询问项目的价格(向量二)。
double ItemCost;
vector<double> Cost;
string ItemName;
vector<string> Item;
while (ItemName != "done")
{
cout << "Item name: "; cin >> ItemName;
Item.push_back(ItemName);// gets item name from use and stores in the vector "Item"
if (ItemName != "done")
{
cout << "Item cost: $"; cin >> ItemCost;
Cost.push_back(ItemCost);// gets cost of item and stores it in the vector "cost"
}
else
{
continue;
}
}
system("CLS");
所以在清除屏幕之后,我希望程序输出一个屏幕,显示项目名称,然后在右边显示成本。然后在下一行对第二项输入执行相同的操作。基本上像这样显示:
cout << Item[0]; cout << " $" << Cost[0];
cout << Item[1]; cout << " $" << Cost[1] << endl;
cout << Item[2]; cout << " $" << Cost[2] << endl;
但是,无论输入多少项,我都希望它这样做,而且按照我上面的方式做显然是一个坏主意,如果他们输入的量小于我在代码中的量,因为程序会试图访问向量占用的内存等之外。这只是举一个我想要的格式的例子。
如果向量大小相同,可以使用简单的for循环来迭代内容:
for (int i = 0; i < Item.size(); ++i) {
cout << Item[i] << " $" << Cost[i] << endl;
}
在运行此代码之前,您可能需要使用调试断言检查这两个向量的大小是否相同:
assert(Item.size() == Cost.size();
或者,您可以使用类似std::min
的东西来只循环两个向量中最小的一个,以防它们大小不同。
我建议使用std::pair
的std::vector
将价格和项目存储在一起,这只是因为它可以跟踪哪个价格与哪个项目相关。这消除了检查两个矢量大小是否相同的需要,并最大限度地减少了发生错误的可能性。然后,使用基于范围的for循环来遍历每一对并打印它们就很简单了。我在下面展示了一个带有一些改进的示例。与简单结构相比,使用std::pair
有很多优点,其中一个优点是包含了在类似std::sort()
的结构中使用的必要布尔函数,如果使用该函数,基本上会按字母顺序对项目列表进行排序。如果您想对代码进行未来验证,这是非常有用的。
double ItemCost;
string ItemName;
vector<std::pair<string, double> > Item;
while (ItemName != "done")
{
cout << "Item name: ";
// Using std::getline() as it terminates the string at a newline.
std::getline(std::cin, ItemName);
if (ItemName != "done")
{
cout << "Item cost: $"; cin >> ItemCost;
Item.push_back(std::make_pair (ItemName,ItemCost));
}
else
{
continue;
}
}
system("CLS");
// Printing here using c++11 range based for loop, I use this extensively
// as it greatly simplifies the code.
for (auto const &i : Item)
{
std::cout << i.first << "tt$" << i.second;
// ^^ Using double tab for better alignment
// instead of spaces.
}
for (size_t index = 0; index < Item.size() && index < Cost.size(); index++)
{
cout << Item[index]; cout << " $" << Cost[index] << endl;
}
但一个更好的想法是有一个vector
来存储类似的东西
struct ItemCost
{
string name;
double cost; // but it's generally safer to store money by pennies in integers
// You can't always count on floating point numbers in comparisons
}
这样一来,项目和成本就永远不会失去同步。
阅读此处了解更多关于浮点在货币等精确事物中失败的原因:比较浮点值有多危险?
相关文章:
- 使用 SFML 和 C++ 将 Pixel 打印到屏幕上
- 使用 fstream 库并在屏幕上打印的文件有问题?
- UE4在屏幕上的打印位置
- Cout 一个字符串可以打印任何内容到屏幕上
- 如何在多维矢量中仅添加特定元素并将内容打印到屏幕
- 如何以CV_16UC1的方式读取JPG图像并在屏幕上打印?
- UNIX API 调用:使用 read() 函数打开文件并将其打印到屏幕上会增加额外的随机字符
- 作为参数传递的打印功能指针导致屏幕上打印"1"
- 在屏幕上打印 X 的形状
- 如何读取二进制文件并在屏幕上打印 3?
- 用putchar在屏幕上打印字符
- C / SFML:使用两个递归调用在屏幕上打印凸形形状仅显示第一个递归调用中的形状,而不是第二个
- 如何在不保存文件的情况下制作打印屏幕并将其发送到FTP服务器?我的工作代码将文件保存到HDD
- 如何在屏幕上打印2^20行C 的整数(1秒钟以下)
- 使用freopen()打印到文件和屏幕
- C++ 强制 std::cout 刷新(打印到屏幕)
- 无法在屏幕上打印 nullptr 的值
- 如何使用Qt/C++和各种显示器拍摄打印屏幕
- C++以二进制形式读取整个文件并将其打印在屏幕上
- Qt:按键事件中的打印屏幕键