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

  • 本文关键字:读取 存储 句子 C++ c++
  • 更新时间 :
  • 英文 :


所以有一个输入文件包含类似的东西

名称1 到达 20 服务 20 名称2 到达 22 服务 11 name3 到达 23 服务 40

我正在尝试在字符串名称中存储名称 1、名称 2、名称 3, 到达 (20, 22, 23( 在 int 到达,服务 (20, 11 ,40( 在 int 服务。 我知道我将不得不使用 while 循环和获取线,但我真的不确定该怎么做。谢谢

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

std::string str = "name1 arrival 20 service 20nname2 arrival 22 service 11nname3 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;
}

最新更新