【问题标题】:Parsing specific string data to variables将特定的字符串数据解析为变量
【发布时间】:2019-10-04 20:33:14
【问题描述】:

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

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;
}

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

为了完成这项任务,我使用了substr()。有什么我盲目地想念的吗?我不确定为什么我的整个stringfile 是空白的,即使我只是打印`std::cout

这里是文本文件的 sn-p,需要对其进行解析以使事情变得更容易

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

我也迷失了如何找到每个部分并将其解析为自己的变量。看起来很简单,但我就是想不通。

【问题讨论】:

  • 此时字符串充满了我正在擦除的不必要的空白 -- 如果您使用std::istringstream,则无需这样做。另外,这些逗号是输入文本文件的一部分吗?
  • 是的。是故意歪斜的。 @PaulMcKenzie
  • @user4581301 我最诚挚的道歉。我离开我的笔记本电脑,我猜我的朋友是个混蛋。对不起

标签: c++


【解决方案1】:

最简单的就是

  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 commas\n" << test << "\n\n";

   // 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

【讨论】:

  • 我认为用空格替换逗号,会比擦除更快
  • @PaulMcKenzie 有没有办法制作一个循环并遍历每个“res”而不是一次全部打印?该文件有不止一行。这是完美的,但我以前从未使用过 strm 并且对它的工作原理感到困惑。假设文件中有 20 行,我想检查每行是否在某个“时间”内将它们分类为早餐/午餐等,这可以使用这种方法吗?
  • 看到struct?创建这些结构的数组或向量。
  • @PaulMcKenzie 我到底该怎么做?我以前从未使用过向量。抱歉,我完全迷失在我的项目中。我读过的所有文档都让我大吃一惊。这是我希望的第一个解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2015-03-19
  • 2015-02-06
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多