c++ - 逐行从文本文件中读取数据,在 C++ 中用多个定界符分隔

标签 c++ file text delimiter getline

我有一个文本文件中的数据,我希望读入并拆分这些数据,然后从中创建一个新对象。

我找到了这段代码:

std::ifstream file("plop");
std::string   line;

while(std::getline(file, line))
{
    std::stringstream   linestream(line);
    std::string         data;
    int                 val1;
    int                 val2;

    std::getline(linestream, data, '\t');

    linestream >> val1 >> val2;
}

读入文本文档并按行拆分。但是,此代码假定分隔符始终是制表符。如果数据有多个定界符,这将指向哪种类型的数据将跟随它会怎样。即假设一个文本文件,例如:

hey, "hi" (hello) [hola]
bye, "by" (byeee) [biii]

我想把数据拆分成

String twoCharacters;
String threeCharacters;
String fourCharacters;
String fiveCharacters;

所以

twoCharacters = hi and by

分隔符是两个" 和

threeCharacters = hey and bye

分隔符是 , 在它之后

任何帮助将不胜感激!谢谢。

最佳答案

您可以使用不同的分隔符继续调用 std::getline():

std::ifstream file("test.txt");

std::string   line;
while(std::getline(file, line))
{
    std::stringstream linestream(line);

    std::string skip;
    std::string item1;
    std::string item2;
    std::string item3;
    std::string item4;

    std::getline(linestream, item1, ',');
    std::getline(linestream, skip, '"');
    std::getline(linestream, item2, '"');
    std::getline(linestream, skip, '(');
    std::getline(linestream, item3, ')');
    std::getline(linestream, skip, '[');
    std::getline(linestream, item4, ']');

    if(linestream) // true if there were no errors reading the stream
    {
        std::cout << item1 << '\n';
        std::cout << item2 << '\n';
        std::cout << item3 << '\n';
        std::cout << item4 << '\n';
    }
}

我使用变量 skip 读取到下一个字段的开头。

关于c++ - 逐行从文本文件中读取数据,在 C++ 中用多个定界符分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29132663/

相关文章:

c++ - CMAKE 链接器没有找到库;但是使用 find_library 找到了库

c++ - 为什么 valgrind 说基本的 SDL 程序正在泄漏内存?

python - 在Python中基本的http文件下载并保存到磁盘?

android - 如何在android中设置带有文本的按钮

android - 将文本文件保存到 android,并添加新行

c++ - 我应该学习 C++ 还是 ASM?

c++ - 错误生成组合问题的非递归方法

linux - 从 Linux 日志文件中学习

c - 如何解决C中读取/写入二进制文件时的段错误

python - 我正在从具有重复值的文件创建一个字典。如何防止循环覆盖现有值?