繁体   English   中英

读取文本文件 C++

[英]Reading a text file C++

我正在尝试从文本文件中检索某些行。 我在用着:

#include <iostream>
#include <fstream>

using namespace std;

void parse_file()
{
    std::ifstream file("VampireV5.txt");
    string str= "Clan";
    string file_contents;
    while (std::getline(file, str))
    {
        file_contents += str;
        file_contents.push_back('\n');

    }
  cout << file_contents;

  file.close();
}

int main()
{
    parse_file();
    return 0;
}

我想得到唯一包含“Clan”的行,直到'\n'。 我试图在while循环中添加一个if,但它没有返回任何东西。

有没有办法让它一次得到 1 行?

您的代码几乎是正确的,如下所示:它逐行读取文件并将内容附加到您的字符串中。

但是,由于您只想要那一行,因此您还需要检查您要查找的内容。

此代码片段应该只为您提供以单词“Clan”开头的行。 如果要检查字符串是否在行中的任何位置,请考虑检查:= string::npos

void parse_file()
{
    std::ifstream file("VampireV5.txt");
    string str;
    string file_contents;
    while (std::getline(file, str))
    {
        if (str.find("Clan") == 0)
        {
            file_contents += str;
            file_contents.push_back('\n');
        }

    }
  cout << file_contents;

  file.close();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM