-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]; 

}

0

2 Answers 2

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" // … } 
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

You have file in line 1 and infile in line 3.
Didn't see that, corrected it. Thanks
i want to store it in a 2D array and the position does matter. Adam should be name[0][0] , John = name [1][0] wendy = name [2][0]
See if it works now! Use std::vector instead of a normal array in c++, its usually easier and better! You can access vectors the same way as arrays. myVector[0][0], for example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.