简体   繁体   中英

How to read from a text file in C++?

I am trying to read a bunch of strings from a text file and saving the characters in a 2D array. The following is my code:

char** fileReader(char* fileName){
    ifstream treeFile;
    treeFile.open(fileName);
    string line;

    vector<string> fileContents;
    int rows=0, columns=0;


    while (getline(treeFile, line )){
        fileContents.push_back(line);
        rows++;
    }

    columns = fileContents.at(0).length();

    char** fileContentsArr;
    fileContentsArr = new char*[rows];

    for (int x=0; x <  rows; x++){
        fileContentsArr[x] = new char[columns];
        for (int y=0; y < columns; y++){
            fileContentsArr[x][y]= fileContents.at(x)[y];
        }
    }

    treeFile.close();
    return fileContentsArr;
}

Output should be:

TTTTTTTT
TTTTTTTT
TTTTFFFT
TTTTTTFF
FFFFTTFF
FFFFTTFF
FFFFTTTT
FFFFTTTF

But instead I am getting only the first 7 characters from each line and only the first 7 strings.

Actual output:

TTTTTTT
TTTTTTT
TTTTFFF
TTTTTTF
FFFFTTF
FFFFTTF
FFFFTTT

What am I doing wrong?

You can use the STL to do almost everything you need here:

vector<string> fileReader(char* fileName){
    ifstream treeFile(fileName);

    vector<string> fileContents(
        (std::istream_iterator<string>(treeFile)),
        std::istream_iterator<string>());

    return fileContents;
}

This creates the vector using its two-iterator constructor, with the first iterator reading from treeFile and producing string s. The second iterator (default-constructed) signifies the end of the file.

Fixed version:

// Changed return type:
std::vector<std::string> fileReader(char* fileName){
  ifstream treeFile;
  treeFile.open(fileName);
  string line;

  std::vector<std::string>  fileContents;
  /// int rows=0, columns=0;

  while (getline(treeFile, line )){
      fileContents.push_back(line);
      rows++;
  }

  // Cut off rest of code, instead:
  return fileContents;
}

If you want to access a character, you can use

std::vector<std::string> data = fileReader("file.txt");
char value = data[3][2];

as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM