简体   繁体   中英

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'. I've tried to add an if inside the while loop but it is not returning anything.

Is there a way to make it get 1 line at once?

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'. If you want to check, whether the string is anywhere on the line, consider checking for := 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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