将特定字符串数据解析为变量
Parsing specific string data to variables
我目前在解析字符串以填充变量时遇到问题。目前,字符串充满了我正在擦除的不必要的空格。之后,我的目标是将数据解析为特定的变量
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
我也不知道如何查找每个部分并将其解析为自己的变量。这似乎很简单,但我就是想不通。
最简单的事情是
- 从输入中删除逗号
- 使用 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
相关文章:
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 如何在变量中插入多种不同长度的数据类型?
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 面临在 if 语句之外打印变量数据的问题 完成使用 Qt 编程
- 有没有办法"QByteArray"变量数据直接放入变量"int"而无需强制转换?
- 如何在一行中从不同的变量(数据类型)创建一个字符数组?
- 从保存变量数据类型的数据结构中检索值,而不指定返回类型
- 从字符串中读取变量数据
- 返回对成员变量数据的引用的开销
- 如何将C 变量数据放入System()函数中
- C++生成器 XE 2 -- 如何在 TEdit 控件中显示变量数据
- 定义C++变量:数据类型(值)
- 静态变量/数据和对象
- 将非成员变量数据传递给构造函数时,如何保存它们并在其他成员函数中使用?C++
- 将变量数据发送到其他类时出现问题
- 如何从变量数据创建std::initializer_list
- 将c++的变量数据类型转换为c#
- 如何在C++中存储变量数据