Reading from TextFile in C++
I am a java/C# developer and i am trying to write a C or C++ code to read data from a text file. this is very easily done in java and c# but not in c or c++.
the textfile i am reading l开发者_JAVA技巧ooks like this:
a,b,c,d,e
1,0,1,1,0
0,1,1,0,0
0,0,0,1,1
i need to store the values in 2 arrays.
the 1st one is a 1D char array which will contain:a b c d e
the 2nd one is a 2D bool array which will contain:
1 0 1 1 0
0 1 1 0 0
0 0 0 1 1
how can i do this?
I suggest you at least make an attempt at what you are trying to do, to help you get started, here is a basic read out of the example data you provided. This example should be simple enough to allow you to expand it to meet other data sets.
#include <iostream>
#include <fstream>
int main() {
const int n_letters = 5;
const int n_columns = 5;
const int n_rows = 3;
char letters[n_letters];
bool booleans[n_rows][n_columns];
std::ifstream stream("myfile.txt");
if (stream) {
for (int i = 0; i < n_letters; ++i) {
stream >> letters[i];
std::cout << letters[i] << ',';
}
std::cout << '\n';
for (int i = 0; i < n_rows; ++i) {
for (int j = 0; j < n_columns; ++j) {
stream >> booleans[i][j];
std::cout << booleans[i][j] << ',';
}
std::cout << '\n';
}
}
return 0;
}
Reads the following text:
a b c d e
1 0 1 1 0
0 1 1 0 0
0 0 0 1 1
And outputs:
a,b,c,d,e
1,0,1,1,0
0,1,1,0,0
0,0,0,1,1
A first comment: when parsing a file, it's often useful to read the file line by line, and then parse each line, using std::istringstream, or boost::regex, or whatever other technique you please. I like boost::regex, because it immediately indicates if there is a syntax error, but carefully designed, istream can as well.
The first thing, in any case, is to specify more precisely the formats: Is there always just one letter? Are the numbers always Just 0 and 1? Are there always exactly five values per line? Until we know that, it's rather difficult to say more.
精彩评论