将特定字符串数据解析为变量

Parsing specific string data to variables

本文关键字:变量 数据 字符串      更新时间:2023-10-16

我目前在解析字符串以填充变量时遇到问题。目前,字符串充满了我正在擦除的不必要的空格。之后,我的目标是将数据解析为特定的变量

Reservation::Reservation() : resID(), resName(""), email(""), people(""), day(""), hour(""){}
Reservation::Reservation(const std::string& m_res) : stringfile(m_res)
{
while (stringfile.find(" ") != std::string::npos) {
auto pos = stringfile.find("");
stringfile.erase(pos);
}
. 
this->resName = stringfile.substr(0,8);
std::cout << resName << std::endl;
}

以上是我的代码片段。目前正在发生的事情是,似乎一切都被抹去了。运行程序测试时,输出只是空格。如果我这样做而不是this->resName = m_res.substr(0,8);,它将返回我想要的,但没有修剪任何空格。

为了完成这项任务,我正在使用substr().我盲目地错过了什么吗?我不确定为什么我的整个stringfile都是空白的,即使我只是打印''std::cout <<字符串文件<<std::endl;'

这是需要解析的文本文件片段,以使事情变得更容易

# ID    : Name    ,             email, # of people, Day, Time
#------------------------------------------------------------
RES-001: John    ,  john@email.com  ,           2,   3,    5

我也不知道如何查找每个部分并将其解析为自己的变量。这似乎很简单,但我就是想不通。

最简单的事情是

  1. 从输入中删除逗号
  2. 使用 std::istringstream 解析输入

下面是一个示例:

#include <sstream>
#include <string>
#include <iostream>
#include <algorithm>
struct record
{
std::string res, firstname, email;
int numpeople, day, time;
};
int main()
{
std::string test = "RES-001: John    ,  john@email.com  ,           2,   3,    5";
// remove the commas by replacing with spaces
std::replace(test.begin(), test.end(), ',', ' ');
std::cout << "This is the string without commasn" << test << "nn";
// now use streams to read in the string
std::istringstream strm(test);
record rec;
strm >> rec.res >> rec.firstname >> rec.email >> rec.numpeople >> rec.day >> rec.time;
// output results
std::cout << rec.res << "n";   
std::cout << rec.firstname << "n";   
std::cout << rec.email << "n";   
std::cout << rec.numpeople << "n";   
std::cout << rec.day << "n";   
std::cout << rec.time << "n";   
}

输出:

This is the string without commas
RES-001: John       john@email.com              2    3     5    
RES-001:
John
john@email.com
2
3
5