-1

For example:

Adam Peter Eric
John Edward
Wendy 

I wanted to store in 3 strings array (each line represents an array), but I am stuck on how to read it line by line.

Here is my code:

 string name [3][3] ;
 ifstream  file ("TTT.txt");
 for (int x = 0; x < 3; x++){
     for (int i = 0; x < 3; i++){
         while (!file.eof()){
             file >> name[x][i];
         } 
     }
 }

 cout << name[0][0];
 cout << name[0][1];
 cout << name[0][2];

 cout << name[1][0];
 cout << name[1][1];
 cout << name[2][0];

}

toblerone_country
  • 577
  • 14
  • 26
Vanishadow
  • 43
  • 1
  • 4

2 Answers2

1

You can use std::getline():

std::ifstream  file ("TTT.txt");
std::string line;
std::string word;
std::vector< std::vector<std::string> > myVector; // use vectors instead of array in c++, they make your life easier and you don't have so many problems with memory allocation
while (std::getline(file, line))
{
    std::istringstream stringStream(line);
    std::vector<std::string> > myTempVector;

    while(stringStream >> word)
    {
        // save to your vector
        myTempVector.push_back(word); // insert word at end of vector
    }
    myVector.push_back(myTempVector); // insert temporary vector in "vector of vectors"
}

Use stl structures in c++ (vector, map, pair). They usually make your life easier and you have less problems with memory allocation.

t.pimentel
  • 1,465
  • 3
  • 17
  • 24
1

You can use std::getline to directly read a full line. After that, just get the individual substrings by using the space as the delimiter:

std::string line;
std::getline(file, line);
size_t position;
while ((position =line.find(" ")) != -1) {
  std::string element = line.substr(0, position);
  // 1. Iteration: element will be "Adam"
  // 2. Iteration: element will be "Peter"
  // …
}
brdigi
  • 135
  • 1
  • 6