1

I am trying to read in rows from a file and save them in to a char* data[] variable with the code that follows:

fstream level;
level.open("level.txt");
char* row;
int i = 0;
char* data[3];

while (level >> row) {
    data[i] = row;
    cout << i << " " << data[i] << "\n";
    i++;
}

for (i = 0; i < 3; i++) {
    cout << "\n " << i << " = " << data[i];
}

level.close();

The contents of the file are as follows:

aaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaa

and the first cout outputs the following, as you'd expect:

0 aaaaaaaaaaaaaaaaaaaaaaaa
1 aaaaaaaaaaaaaaaaaaaaaaaa
2 aaaaaaaaaaaaaaaaaaaaaaaa

but then the second one outputs the following:

0 =
1 = 
2 = 

as If all the data from data[] has been erased. Can anyone advise me as to why this is happening?

thanks for your help.

stell1315
  • 153
  • 1
  • 2
  • 9
  • 1
    `std::ifstream` doesn't work this way. Read all details here: http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/ – Flovdis Apr 05 '14 at 17:41
  • 1
    You're writing to unallocated space + invoking UB. Consider using `std::string` , `std::vector` and `std::getline()` – P0W Apr 05 '14 at 17:42
  • which bit is writing to unallocated space? – stell1315 Apr 05 '14 at 17:44
  • thanks, changing it to string rather than char* works! – stell1315 Apr 05 '14 at 17:46
  • possible duplicate of [C++: Read file line by line](http://stackoverflow.com/questions/7868936/c-read-file-line-by-line) – jww Apr 05 '14 at 17:49

2 Answers2

3

Since you use the standard library (cout) why not use string instead of char* ?

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

using namespace std;

fstream level;
level.open("level.txt");
string row;
int i = 0;
string data[3];

while ((i<3) && (level >> row)) {
    data[i] = row;
    cout << i << " " << data[i] << "\n";
    i++;
}

for (i = 0; i < 3; i++) {
    cout << "\n " << i << " = " << data[i];
}

level.close();
Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
1

You are using pointers without allocating memory to them! You can allocate them by your self, but then you have to take care if you are reading more lines than you have memory allocated. Pleas try this junk of code. It uses std vectors and strings and you don't have to allocate the memory. You may need to enable the std-C11 switch of you compiler (std::string::push_back)

fstream level;
level.open("level.txt");
char row;
int i = 0;
std::vector<std::string> > data;
data.push_back(std::string());

while (level >> row) {
    if (row!='\n'){
        data.back().push_back(row);
        cout << row;
    else{
        data.push_back(std::string());
        cout << "\n";
}

for (int i = 0; i < data.size(); i++) {
    cout << "\n " << i << " = " << data[i].c_str();
}

level.close();
ROTA
  • 101
  • 3