0

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?

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
Isma Hène
  • 49
  • 5
  • What exactly are you getting? Does the file exist? Was it opened successfully? Have you tried outputting debug messages? – Refugnic Eternium Nov 27 '20 at 10:02
  • the variable file_content contains the text until its end. I want it to get only that line containing the word 'Clan' ; – Isma Hène Nov 27 '20 at 10:04
  • Furthermore, you aren't checking the line contents for anything. Consider putting `if (str.find("Clan") == 0)` to check, whether the line starts with the word you're looking for. – Refugnic Eternium Nov 27 '20 at 10:04
  • 1
    If I understand well, you have to check if the string "Clan" is included in the string `str`. You may find related information [here](https://stackoverflow.com/q/2340281/10553341). Then, you can break in the while loop when you got this line – Damien Nov 27 '20 at 10:05
  • @Damien Merci beaucoup, this is exactly what I needed. – Isma Hène Nov 27 '20 at 10:11
  • @IsmaHène If your problem has been solved, it would be nice if you clicked the checkmark on the answer that helped you resolve it. This lets others know that your problem has been solved. – Refugnic Eternium Nov 27 '20 at 10:18

1 Answers1

2

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();
}
Refugnic Eternium
  • 4,089
  • 1
  • 15
  • 24