gpt4 book ai didi

c++ - 如何在 C++ 中将文本文件读入二维动态 vector ?

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:50 24 4
gpt4 key购买 nike

我有一个包含两列和未知行数的文本文件。所以我想将两列加载到动态二维 vector 中。到目前为止,这是我所拥有的,它不起作用。如果这是一维的,我知道该怎么做。空白分隔两列。因为我正在阅读 2 列,所以我只需要 2 个大小为 n 的 vector 。

vector<vector<string> > component;
ifstream in_file("/tmp/FW.txt", ios::binary);

//Check if the file is open
if(!in_file.is_open())
{
cout << "File not opened..." << endl;
exit (1);
}

for(int i=0; !in_file.eof(); i++)
{
in_file >> component.push_back();
//component.push_back(in_file);
}

有人可以告诉我如何让它工作吗?另外,如果您能告诉我如何打印二维 vector ,使其看起来像原始文件,那也很好。这需要在 Linux(Red hat) 上运行

最佳答案

怎么样:

vector< vector<string> > component;
ifstream in_file("/tmp/FW.txt"); // N.B., not ios::binary since you're reading text strings
vector<string> vs( 2 );
// Assume they are separated by just whitespace
while( in_file >> vs[0] >> vs[1] )
{
component.push_back( vs );
}

关于c++ - 如何在 C++ 中将文本文件读入二维动态 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10147554/

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