C++-如何在 C++ 中解析带分隔符的字符串?

问题描述 投票:0回答:1

这花了我很长时间才弄清楚,我研究了很多不同的例子,但有些看起来很复杂,并且出于 A、B、C 的原因,其中有额外的步骤......这就是我需要的 - 让我们说你有一个字符串,我们将其称为字符串 A

字符串 A =“我

所以分隔符当然是 '<'

如何解析这个字符串以取出分隔符?然后我必须创建这些字符串的对象并将它们添加到指针数组中。

请参阅下面的示例:) 请忽略顶部的所有指令。我讨厌猜测我需要什么和不需要什么,所以我开始在所有文件中包含我需要的每一个文件(除了在其他文件中包含文件)。我花了 6 个多小时研究解析,但一无所获,所以我今晚正式结束了......

我猜我也对指针感到困惑,因为我认为下面的行将是一个指针,用于从学生头文件中的 Student 类获取数据,并让它创建一个指针数组,然后我将使用该指针填充对象下面的“add”方法........但它告诉我-无法使用“string *”类型的右值(又名“basic_string *”)初始化类型为“Student *”的成员子对象....在尝试学习这些材料时,我感觉自己向前迈出了一步,然后撞到了墙上,然后又弹回了两步......

Student* classRosterArray = new string[5];
#pragma once
#include <stdio.h>
#include <string>
#include <iostream>
#include <print>
#include <iomanip>
#include "student.hpp"
using namespace std;

class Roster
{
private:
    // Array of pointers, size = 5-- I thought I was supposed to use a pointer to reference the Student class.... and call the new array which we are adding objects into classRosterArray?
    Student* classRosterArray = new string[5];
    //string* classRosterArray = new string[5]; --Is this what is needed??
    
public:
    void parse(string row);
    void add(string studentId,
             string firstName,
             string lastName,
             string emailAddress,
             int age,
             int daysToComp3Course,
             DegreeProgram degreeProgram);
};
c++ arrays object parsing delimiter
1个回答
0
投票

如何解析这个字符串以取出分隔符?

要提取每个单词,请使用 std::getlinestd::istringstream:

#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::string A = "I<Like<Butterscotch<candies<so<much";
    std::istringstream strm(A);
    std::string word;
    while (std::getline(strm, word, '<'))
        std::cout << word << "\n";
}

输出:

I
Like
Butterscotch
candies
so
much
© www.soinside.com 2019 - 2024. All rights reserved.