【问题标题】:Need to read a line of text from an archive.txt until "hhh" its found and then go to the next line需要从 archive.txt 中读取一行文本,直到找到“hhh”,然后转到下一行
【发布时间】:2020-05-22 00:46:42
【问题描述】:

我的老师给了我这个作业,我需要从文件中读取单词,然后用它们做一些事情。我的问题是这些词必须以"hhh"结尾,例如:groundhhhwallhhh等。

在寻找一种方法时,我想出了getline 库中的getline 函数。问题是 getline(a,b,c) 使用 3 个参数,其中第三个参数是读取直到找到 cc 必须是 char,所以它对我不起作用。

本质上,我想要实现的是从文件中读取一个单词,例如"egghhh",并使其如此,如果读取"hhh",则意味着该行在那里完成,我收到"egg"作为这个词。我的老师用“哨兵”这个词来描述这个hhh的东西。

这是我的尝试:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

ifstream read_archive;

void showListWords(){

    string word;

    string sentinel = "hhh";

    while (getline(read_archive,word,sentinel)){

        cout << word << endl;
    }
}

void openReadArchive(){

    read_archive.open("words.txt");

    if(read_archive.fail())

        cout << "There is something wrong with the archive" << endl;

}

【问题讨论】:

    标签: c++ c fstream getline


    【解决方案1】:

    如您所见,std::getline() 仅允许您为停止读取的“哨兵”指定 1 个char,其中'\n'(换行符)是默认值。

    您可以使用此默认值将文件中的整行文本读入std::string,然后将该字符串放入std::istringstream 并从该流中读取单词,直到到达流的末尾或者你找到一个以"hhh"结尾的词,例如:

    #include <sstream>
    #include <limits>
    
    void showListWords()
    {
        string line, word;
        string sentinel = "hhh";
    
        while (getline(read_archive, line))
        {
            istringstream iss(line);
            while (iss >> word)
            {
                if (word.length() > sentinel.length())
                {
                    string::size_type index = word.length() - sentinel.length();
                    if (word.compare(index, sentinel.length(), sentinel) == 0)
                    {
                        word.resize(index);
                        iss.ignore(numeric_limits<streamsize>::max());
                    }
                }
    
                cout << word << endl;
            }
        }
    }
    

    在这种情况下,您也可以只从原始文件流中读取单词,当您找到以 "hhh"ignore() 结尾的单词时停止当前行的其余部分,然后继续从下一行读取单词,例如:

    #include <limits>
    
    void showListWords()
    {
        string word;
        string sentinel = "hhh";
    
        while (read_archive >> word)
        {
            if (word.length() > sentinel.length())
            {
                string::size_type index = word.length() - sentinel.length();
                if (word.compare(index, sentinel.length(), sentinel) == 0)
                {
                    word.resize(index);
                    read_archive.ignore(numeric_limits<streamsize>:max, '\n');
                }
            }
    
            cout << word << endl;
        }
    }
    

    【讨论】:

    • 非常感谢,这真的很有帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    相关资源
    最近更新 更多