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?

6
  • What exactly are you getting? Does the file exist? Was it opened successfully? Have you tried outputting debug messages? Commented Nov 27, 2020 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' ; Commented Nov 27, 2020 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. Commented Nov 27, 2020 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. Then, you can break in the while loop when you got this line Commented Nov 27, 2020 at 10:05
  • @Damien Merci beaucoup, this is exactly what I needed. Commented Nov 27, 2020 at 10:11

1 Answer 1

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(); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.