【问题标题】:Reading a file into memory C++: Is there a getline() for std::strings将文件读入内存 C++:std::strings 是否有 getline()
【发布时间】:2019-04-12 05:08:35
【问题描述】:

我被要求更新读取文本文件并将其解析为特定字符串的代码。

基本上不是每次都打开文本文件,而是想将文本文件读入内存并在对象的持续时间内拥有它。

我想知道是否有与 getline() 类似的函数可以用于 std::string,就像我可以用于 std::ifstream 一样。

我意识到我可以只使用 while/for 循环,但我很好奇是否还有其他方法。这是我目前正在做的事情:

file.txt: (\n 代表换行符)

file.txt

我的代码:

ifstream file("/tmp/file.txt");
int argIndex = 0;
std::string arg,line,substring,whatIneed1,whatIneed2;
if(file)
{
    while(std::getline(file,line))
    {
        if(line.find("3421",0) != string::npos)
        {
            std::getline(file,line);
            std::getline(file,line);
            std::stringstream ss1(line);
            std::getline(file,line);
            std::stringstream ss2(line);
            while( ss1 >> arg)
            {
                if( argIndex==0)
                {
                    whatIneed1 = arg;
                }
                argIndex++;
             }
             argIndex=0;
            while( ss2 >> arg)
            {
                if( argIndex==0)
                {
                    whatIneed2 = arg;
                }
                argIndex++;
             }
             argIndex=0;
         }
     }
 }

whatIneed1=="whatIneed1" 和 whatIneed2=="whatIneed2" 到底在哪里。

有没有办法使用 getline() 之类的函数将 file.txt 存储在 std::string 而不是 std::ifstream asnd 中?我喜欢 getline(),因为它使获取文件的下一行变得容易得多。

【问题讨论】:

  • 搜索“啜饮”
  • 没有。 std::string 对文件一无所知。在 C++ 中读取文件的唯一方法是使用文件流之一。请注意,有一些方法可以从 C++ 之外的文件中读取,但这些方法不太可能支持 std::string。也不清楚你的最终目标是什么。

标签: c++ fileinputstream stringstream string-parsing stdstring


【解决方案1】:

如果您已经将数据读入字符串,则可以使用std::stringstream 将其转换为与getline 兼容的类文件对象。

std::stringstream ss;
ss.str(file_contents_str);
std::string line;
while (std::getline(ss, line))
    // ...

【讨论】:

    【解决方案2】:

    与其抓住一条线然后尝试从中提取一件事,为什么不提取一件事,然后丢弃该线?

    std::string whatIneed1, whatIneed2, ignored;
    if(ifstream file("/tmp/file.txt"))
    {
        for(std::string line; std::getline(file,line);)
        {
            if(line.find("3421",0) != string::npos)
            {
                std::getline(file, ignored);
                file >> whatIneed1;
                std::getline(file, ignored);
                file >> whatIneed2;
                std::getline(file, ignored);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 2016-07-29
      • 2020-04-05
      • 1970-01-01
      相关资源
      最近更新 更多