How to read an unknown contents of a text file into a 2d array
I am trying to read the unknown contents of a text file into a 2D array and have it come out looking like:
M [0] [0]=2 M [0] [1]=1 M [0] [2]=0
M [1] [0]=0 M [1] [1]=1 M [1] [2]=3
M [2] [0]=8 M [2] [1]=9 M [2] [2]=1
M [3] [0]=3 M [3] [1]=5 M [3] [2]=2
when the text file looks like this:
2
1 0
0 1
3
8 9 1
3 5 2
-2 3 -1
0
The zero at the end shows the end o开发者_如何学Cf the file.
My problem is the array can be a max size of 10X10 so there is no way of knowing what the size of the 2D array is and how to get it to look like i have shown above.
Any ideas?
Just use 'fstream'. It ignores new lines and works just like 'iostream'. You just need to keep track of your matrix row and column.
//open "myFileName.txt" with an input file stream
std::ifstream inputFile("myFileName.txt");
while(!inputFile.eof()) //Check for end-of-file character
{
//do this while keeping track of your matrix position
inputFile >> M [curRow] [curColumn]
}
inputFile.close();
And don't forget to include the library:
#include <fstream>
Edit: The >>
operator will also attempt to auto-cast the input as whatever type you are using:
double dTemp;
int iTemp;
std::string sTemp;
std::ifstream in("myFile.txt");
in >> dTemp; //input cast as double
in >> iTemp; //input cast as integer
in >> sTemp; //input cast as string
in.close();
Edit: Get the number of elements of the file
int temp, numberOfInputs;
while(!inputFile.eof())
{
inputFile >> temp;
++numberOfInputs;
}
inputFile.seekg(0, std::ios::beg); //Go to beginning of file
Once you have the number of inputs you can use that to figure out the number of rows and colums.
For some dimensions N x M
char c;
int x;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
c = fgetc(file);
if(c == ' ') continue;
if(c == EOF) return;
if(c == '-')
{
c = fgetc(file);
x = -1 * ((int)c);
} else {
x = c;
}
if(x == 0)
{
array[i][j] = x;
} else {
return;
}
}
}
But if you're talking about "what's the size of the matrix required to store these" then you're going to need a way to figure out what dimensions you want.
Try:
#include <vector>
#include <fstream>
#include <iostream>
int main()
{
std::ifstream file("plop.dat");
if(!file)
{
std::cerr << "Failed to open File\n";
return 1;
}
// Keep looping until we are done.
while(true)
{
int size;
file >> size;
// You said a size zero indicates termination.
if (size == 0)
{ break;
}
// Create a square 2D vector (Vector inside a Vector)
std::vector<std::vector<int> > matrix(size, std::vector<int>(size, 0));
// Loop over each axis
for(int x = 0;x < size; ++x)
{
for(int y = 0;y < size; ++y)
{
// Read one number for each location.
// The operator >> automatically skips white space
// White Space includes newline and tab. So it should work
// perfectly if the input is OK. But it is hard to detect
// an error in the format of the file.
file >> matrix[x][y];
}
}
}
}
~
So all row of the array have 3 values?
Simply read the values into the array keeping a count of which column you are in and ignore the newlines?
Look at getline
getline
and stringstream
to read, vector< vector<int> >
to store.
Edit: Oh, so the size is always N*N? Then just read using while(cin>>x) { if (cin.good()) ...; }
into a vector<int>
, check the total size, and split into vector< vector<int> >
Single and multi-dimensional C arrays are just contiguous pieces of memory. The difference is more syntactical in terms of what indexing into the array does: for a 2-dimensional array it just multiplies one dimension by the size of the other dimension before adding the second dimension to find the offset.
So to solve:
- read the values into a std::vector (other answers have sugegsted ways to do this)
- work out the size (integer square root of myArray.size())
calculate the index as, e.g.:
int idx(int size, int d1, int d2) { return (d1*size)+d2; }
Return the vector element at the index e.g.:
for (int d1 = 0; d1 < size; d1++) { for (int d2 = 0; d2 < size; d2++) std::cout << "M [" << d1 << "] [" << d2 << "]=" << myArray[idx(size, d1, d2)] << " "; std::cout << std::endl; }
gives me:
$ g++ arr.cpp && ./a.out
M[0][0]=2 M[0][1]=1 M[0][2]=0
M[1][0]=0 M[1][1]=1 M[1][2]=3
M[2][0]=8 M[2][1]=9 M[2][2]=1
精彩评论