使用同一行C++中引入的数据

use datas introduced in the same line C++

本文关键字:C++ 数据 一行      更新时间:2023-10-16

我试图获取和比较不同的数据。 我必须带上产品的名称及其价格 (橙汁,5( 但我的问题是我不知道如何为超过 1 种产品做到这一点。 我使用 Getline 来提供数据,但我不知道他们会介绍多少产品,以及 idk 如何停止循环。

(橙汁,5;牛奶,7;(

while (?????????) {
getline(cin, product, ',');
getline(cin, price, ';');
products[num] = product;
proces[num] = atoi(proce.c_str());
num++;

}

如果您不知道某个单词的大小并退出,则可以进行无限的用户输入。下面是一个示例代码。请注意,就在getline(cin, product, ',')之后,我放置了一个if语句。如果用户此时输入exit,,程序将退出。

我也用过向量。向量就像数组,但它们的大小可以在运行时更改,因此您可以在其中存储无限(与内存一样多(数据。

最后一部分是显示输出。

这是解决问题的示例方法,您可以应用任何您喜欢的方法。

#include <iostream>
#include <string>
#include <vector>
std::string product;
std::string price;
std::vector<std::string> products;
std::vector<int> prices;
int main()
{
unsigned num = 0;
while (true)
{
getline(std::cin, product, ',');
if(product == "exit")
break;
getline(std::cin, price, ';');
products.push_back(product);
prices.push_back(atoi(price.c_str()));
num++;
}
for(unsigned i = 0; i < products.size(); i++)
{
std::cout << "Product: " << products.at(i) << "n";
std::cout << "Price  : " << prices.at(i) << "n";
}
}

我使用的输入:

orange juice,5;milk,7;exit,

产生的输出:

Product: orange juice
Price  : 5
Product: milk
Price  : 7

试试

bool check=false;
if(!getline(cin, price, ';'))check=true;
...
if(check)break;

你应该在这里使用std::vector而不是array

我只是向前看一下 stdin 缓冲区,看看该行是否被终止(通过输入 =n.(

#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string product;
std::string price;
std::vector<std::pair<std::string, int>> product_price;
while (std::cin.peek() != 'n')
{
std::getline(std::cin, product, ',');
std::getline(std::cin, price, ';');
product_price.push_back(make_pair(product,std::stoi(price)));
}
for (auto& item : product_price)
{
std::cout
<< "Product: " << item.first << "n"
<< "Price  : " << item.second << "n";
}
return 0;
}