This topic is 4736 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hello all I am trying o load a two demensional array with numbers stored in a text file. During this process I want to implement a line of code everytime a new line is read, and I am having problems with this code:
	int array[MAXCHARS][MAXCHARS];
int position, temp;
int colum = 0;
int row = 0;
ifstream ifile;
ifile.open("somefile.txt");

ifile >> temp;
while(!ifile.eof())
{
array[colum][row] = temp;
cout << array[colum][row] << " ";
colum ++;
if(temp == '\n')
{
row++;
cout << endl;
}
ifile >> temp;

}


Thanks for any help.

Share on other sites
I was going to say that when you get to that newline, and increment your row, you probably want to reset your column index back to zero. However, in a 4x4 matrix for example, the 5th column of the 1st row is equal to the 1st column of the 2nd row anyway.

What exactly is the problem you're having? Is there anything being displayed incorrectly? Or are you overflowing the array itself?

Share on other sites
I think the information I am looking for is, without using some brand of getline process how can I set the if statement to execute everytime a new line of the text file starts?

right now the code sets only the first part of the array [0][0] and then moves on to [0][1] then it moves up [1][1], [2][1], [3][1] etc.

I would like the array to look as the file does:

4 5 6 9 7 8
4 5 6 7 5 5 22 3 6 4
45 6 5
44 6 9 8
5 6 9 7 8
56 9 7 8 4 5 3

where array[1][6] == 22

Share on other sites
When you increment row, dont you want to reset column? you'll get an array-index-out-of-bounds related error eventually..

im not sure if this will work, but try it:
int array[MAXCHARS][MAXCHARS];int position, temp;int colum = 0;int row = 0;ifstream ifile;ifile.open("somefile.txt");ifile >> temp;while(!ifile.eof()){				array[colum][row] = temp;	cout << array[colum][row] << " ";	colum ++;	if( ifile.peek() == '\n' ) { // istream::peek		row++;		cout << endl;	}	ifile >> temp;}

Share on other sites
Thanks alot the .peek worked great!

Share on other sites
#include <vector>#include <sstream>#include <string>#include <iostream>using namespace std;// ...vector<vector<int> > data;ifstream file("data.dat");string line;while (getline(file, line)) {  stringstream parser(line);  vector<int> parsedLine;  int item;  while (parser >> item) parsedLine.push_back(item);  data.push_back(parsedLine);}

• 16
• 9
• 13
• 41
• 15