I'm trying to read from a file from the terminal. The first and the second line of the file consist of the row number and column. While other lines consist of matrix character contents. I was able to read the first and second lines and stores their values and accordingly assign matrix size. But I cant figure out how to read the remaining part.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream f;
f.open(argv[1]);
int row, col;
f >> row;
f >> col;
char matrix[row][col];
char c;
int i = 0, j = 0;
while (!f.eof()) {
//TODO
}
f.close();
return 0;
}
EDIT1: The file contents:
11
11
X XXXXXXXXX
X X X
X XXXXX X X
X X X X
XXXXX XXX X
X X X X
X X XX X X
X X X X
X XXXXXXX X
X X
XXXXXXXXXXX
Try this:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
int main(int argc, char *argv[])
{
std::vector<std::string> v;
std::ifstream in(argv[1]);
std::string line;
int row, col;
in >> row >> col;
while (std::getline(in, line))
{
if (!line.empty())
v.push_back(line);
}
}
You didn't show the file contents, so I assume this should work :
int i,j;
for( i=0; i < row; ++i)
for( j=0; j < col; ++j)
f >> matrix[i][j] ;
No need to check end of file, if file has exactly row*col
characters separated by space
As per your updated pose you need to read white space too So try this,
for( i=0; i < row; i++)
for( j=0; j < col; j++)
f >> std::noskipws >> matrix[i][j] ; // Don't skip white-space
I haven't tested this but I assume you might have to do some other tweaks (may be increase row to 12).
Also to clear the noskipws
flag use f.unsetf(ios_base::skipws);
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.