使用同一行C++中引入的数据
use datas introduced in the same line C++
我试图获取和比较不同的数据。 我必须带上产品的名称及其价格 (橙汁,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;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 使用流处理接收到的数据
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在cuda线程之间共享大量常量数据
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中序列化结构数据
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 在c代码之间共享数据的最佳方式
- 链表,反向函数,数据结构
- 数据成员SFINAE的C++17测试:gcc vs clang
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何对点云数据进行排序
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 在运行时处理类型擦除的数据-如何不重新发明轮子