简体   繁体   English

读取文本文件 C++

[英]Reading a text file C++

I'm trying to retrieve certain lines from a text file.我正在尝试从文本文件中检索某些行。 I'm using:我在用着:

#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;
}

I want to get that one and only line containing "Clan" until '\n'.我想得到唯一包含“Clan”的行,直到'\n'。 I've tried to add an if inside the while loop but it is not returning anything.我试图在while循环中添加一个if,但它没有返回任何东西。

Is there a way to make it get 1 line at once?有没有办法让它一次得到 1 行?

Your code is almost correct as in: It reads the file line by line and appends the contents to your string.您的代码几乎是正确的,如下所示:它逐行读取文件并将内容附加到您的字符串中。

However since you only want that one line, you also need to check for what you are looking for.但是,由于您只想要那一行,因此您还需要检查您要查找的内容。

This code snippet should give you only the line, which starts with the word 'Clan'.此代码片段应该只为您提供以单词“Clan”开头的行。 If you want to check, whether the string is anywhere on the line, consider checking for := string::npos .如果要检查字符串是否在行中的任何位置,请考虑检查:= 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