0

Would like to fill an array one line at a time from the file "Hello.cpp". However if I do it the way below I fill the entire file [w] times instead of just grabbing one line from the file for each iteration of i.

If I remove the { } from getline then the array is filled with the last line of "Hello.cpp" [w] times.

I am not sure how to get a new [i] each time from the Hello.cpp file.

#include <string>
#include <fstream>
#include <iostream>

using namespace std;

int main() {
int w=0;
ifstream in("Hello.cpp"); 
string s;
while(getline(in, s))
     w=w+1; //first count the number of lines in the file for the array

string a[w];//make an array big enough for the file
for(int i = 0; i < w ; i++) {
    ifstream in("Hello.cpp");
    string s;
    while(getline(in, s)){
        a[i] = s;
        cout << i + 1 << " " << s << endl;
   }
}
Eric Brown
  • 13,774
  • 7
  • 30
  • 71
user2899211
  • 63
  • 1
  • 8
  • 2
    That's not valid C++. You need a compile-time constant as your array size. Normally, without a custom line iterator, that's done by pushing lines onto a vector as they're read. – chris Oct 20 '13 at 03:06
  • 1. count lines 2. create C-style array to hold lines... does it have to be an array? – LihO Oct 20 '13 at 03:09
  • Possible duplicate http://stackoverflow.com/questions/8365013/reading-line-from-text-file-and-putting-the-strings-into-a-vector – Mike Makuch Oct 20 '13 at 03:10

1 Answers1

0

I would close your file before reopening it (best practice).

Looks to me like you need to move your file open (ifstream constructor) outside of your for (do you really want to open the file w times)? Since you bother to count the lines first don't you really want something like this:

ifstream in1("Hello.cpp");
for(int i = 0; i < w ; i++) {
    getline(in1, a[i]);
    cout << i + 1 << " " << a[i] << endl;
 }
Dweeberly
  • 4,668
  • 2
  • 22
  • 41