Phantom4567
Phantom4567

Reputation: 1

How to read individual lines of a text file using C++

Ok, so its been a while since i messed with reading and writing file and i have just about forgot everything i learned. So, i am currently just trying to figure out how to read specific lines from a text file and output that said line into the command prompt. Here is my code that i am having issues with:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
ifstream input;
int lineN=0;
string line[lineN];
input.open("input.txt");

getline(input, line[lineN]);
cout << line[lineN];
}

As it currently is, it will read the first line of the text file no problem. However, if i change the variable lineN(which stands for line number) to 1 to read the second line, it crashes the prompt. I have no idea what it is i am doing wrong. I have tried researching this problem, but everyone's answer is too vague (That or i'm just too dumb). If you could help me out that would great.

Upvotes: 0

Views: 1467

Answers (2)

Christophe
Christophe

Reputation: 73617

The problem is that you define here an empty array of strings and arrays are not dynamic:

int lineN=0;
string line[lineN];

When you change lineN to 1, nothing changes in the array, and you'll get out of bound !

The bettter way would be to use vectors:

vector<string> line;  

Read in a temporary string:

string current_line;  
getline(input, current_line);

and add it to your vector:

line.push_back(current_line); 

Putting all this in a nice loop would be more useful:

 string current_line; 
 while (getline(input, current_line)) {
        line.push_back(current_line); 
 }

You may access any line later, by using line[i] exactly with your array, as long as i< line.size(). Or you may iterate easily throug all its content:

 for (string x : line)  {    // means for every x in line[]
     cout<< x<<endl; 
 }  

Upvotes: 4

Zaiborg
Zaiborg

Reputation: 2522

you allocate a array of size 0 ...

you will find answer of what will happen can be found here: C++ new int[0] -- will it allocate memory?

Upvotes: 1

Related Questions