0

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.

  • string line[5] will define an array of the size 5, with the accessible indexes [0]-[4], note [5] is _not_ a valid index. That your program doesn't crash with lineN = 1 is pure "luck". In any way though, this just tells getline where to store what it reads - not from where to read it. You'll always read the first line of the text file this way. And getline never getting hold of the value "lineN" should be absolutely obvious and self-evident to you, if it's not try learning the basics of scopes and function calls again. – cooky451 Oct 01 '14 at 16:57
  • 1
    `getline(input, line[lineN]);` - You are accessing an element outside the bounds of an array resulting in undefined behavior. – Captain Obvlious Oct 01 '14 at 16:58
  • This shouldn't even compile: `std::string line[lineN];` is not legal in C++. You are compiling in C++, aren't you? (With all the compilers I know, you need special options to compile in C++, rather than in some custom language derived from C++.) – James Kanze Oct 01 '14 at 17:23

2 Answers2

4

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; 
 }  
Christophe
  • 68,716
  • 7
  • 72
  • 138
1

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?

Community
  • 1
  • 1
Zaiborg
  • 2,492
  • 19
  • 28