我同意约阿希姆的观点。此外,在阅读文件时,使用back_inserter
和istream_iterator
让stringstream
您的生活更轻松:
vector<vector<double> > contents;
/* read file */
{
ifstream inFile( "data.txt" );
for ( string line; inFile; getline( inFile, line ) ) {
stringstream line_stream( line );
vector<double> row;
copy( istream_iterator<double>( line_stream ), istream_iterator<double>(),
back_inserter(row) );
contents.push_back( row );
}
}
这会将整个文件读入contents
. 您需要包括sstream
、algorithm
、iterator
、iosrteam
、fstream
和string
。vector
Now you can easily process your file with a for
loop and accessing the numbers with contents[i][j]
. If I understand you correctly this is what I think you want to do:
/* process file */
unsigned int n = contents.size();
for ( unsigned int i=0; i < n; ++i ) {
vector<double> row( 5, 0. );
bool add_row = false;
if ( contents[i].size() >= 5 ) {
for ( unsigned int j=3; j<4; ++j ) {
double value = contents[i][j];
contents[i][j] = 0.;
if ( value > 0 ) {
add_row = true;
row[j-3] = value;
}
}
if ( add_row == true ) {
contents.push_back( row );
}
}
}
Now to write the file to stdout, simply:
/* write file */
for ( unsigned int i=0; i < contents.size(); ++i ) {
copy( contents[i].begin(), contents[i].end(), ostream_iterator<double>( cout, " " ) );
cout << endl;
}