gpt4 book ai didi

C++ 编辑文本文件

转载 作者:行者123 更新时间:2023-11-28 03:07:56 24 4
gpt4 key购买 nike

问题是文本文件编辑中的数据。文本文件包含五列。

1 | 2 | 3 | 4 | 5 |

1 2 4 4 1
2 3 4 4 3
3 4 5 0 0

目标是移动到上面第 1 列和第 2 列的第 4 列和第 5 列(值 > 0)或跟进:

1 | 2 | 3 | 4 | 5 |

1 2 4 0 0
2 3 4 0 0
3 4 5 0 0
4 1 0 0 0
4 3 0 0 0

如何实现?谁能告诉我如何使用 C++ std::vector 执行此操作的示例?

那将不胜感激。

最佳答案

我同意约阿希姆的观点。此外,使用 back_inserteristream_iteratorstringstream 让您在读取文件时更轻松:

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 );
}
}

这会将整个文件读入内容。您需要包含 sstreamalgorithmiteratoriosrteamfstream , stringvector.

现在您可以使用 for 循环轻松处理文件并使用 contents[i][j] 访问数字。如果我对你的理解正确,这就是我认为你想要做的:

/* 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 );
}
}
}

现在将文件写入标准输出,只需:

/* write file */
for ( unsigned int i=0; i < contents.size(); ++i ) {
copy( contents[i].begin(), contents[i].end(), ostream_iterator<double>( cout, " " ) );
cout << endl;
}

关于C++ 编辑文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19226616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com