Domanda

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.

È stato utile?

Soluzione

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();

Altri suggerimenti

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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top