gpt4 book ai didi

c++如何从句子中读取和存储值

转载 作者:行者123 更新时间:2023-11-28 01:46:19 25 4
gpt4 key购买 nike

所以有一个包含类似内容的输入文件

name1 arrival 20 service 20name2 arrival 22 service 11name3 arrival 23 service 40 

我正在尝试将 name1、name2、name3 存储在字符串名称中,int arrival 中的 arrivals (20, 22, 23),int service 中的 service (20, 11,40)。我知道我必须使用 while 循环和 getline,但我不确定该怎么做。谢谢

最佳答案

为您整理了一个快速示例程序。基本上,您需要使用 stringstream 来存储到您需要的任何数据结构中。根据您使用的架构,可能会有特殊的解决方案,但希望这能让您入门。

  std::string str = "name1 arrival 20 service 20\nname2 arrival 22 service 11\nname3 arrival 23 service 40";
std::stringstream iss(str);

// Create temporary variable to store each line
std::string line;

// Data to hold each item
std::string name[3];
int arrival[3];
int service[3];
std::string trash; // For throwing out data

// Read stream line by line
int index = 0;
while (getline(iss, line))
{
// Parse the line
std::stringstream lineStream(line);

// Read each attribute into the appropriate data structure
lineStream >> name[index];
lineStream >> trash;
lineStream >> arrival[index];
lineStream >> trash;
lineStream >> service[index];

// Increment index
++index;
}

// Print out the results
for (int i = 0; i < 3; ++i)
{
std::cout << "Index[" << i << "]: " << name[i]
<< ", " << arrival[i] << ", " << service[i]
<< std::endl;
}

关于c++如何从句子中读取和存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44940833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com