Isma Hène
Isma Hène

Reputation: 49

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?

Upvotes: 0

Views: 917

Answers (1)

Refugnic Eternium
Refugnic Eternium

Reputation: 4291

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();
}

Upvotes: 2

Related Questions