gpt4 book ai didi

c++ - 从 stringstream 中提取到 2D vector 中

转载 作者:太空宇宙 更新时间:2023-11-04 13:42:47 25 4
gpt4 key购买 nike

这可能是一个愚蠢的问题,但无论如何:我想从一个 .txt 文件中获取数字,其中包含图形的邻接矩阵,文件的第一行仅包含节点数。

10

-1 5 3 -1 -1 -1 -1 -1 -1 -1

5 -1 -1 4 -1 -1 -1 -1 -1 -1

3 -1 -1 -1 -1 9 7 6 -1 -1

-1 4 -1 -1 2 -1 -1 -1 -1 -1

-1 -1 -1 2 -1 -1 -1 -1 -1 -1

-1 -1 9 -1 -1 -1 -1 -1 -1 -1

-1 -1 7 -1 -1 -1 -1 -1 4 2

-1 -1 6 -1 -1 -1 -1 -1 -1 -1

-1 -1 -1 -1 -1 -1 4 -1 -1 -1

-1 -1 -1 -1 -1 -1 2 -1 -1 -1

为什么它不能以正确的方式工作?输出如下:

10

10 0 0 0 0 0 0 0 0 0

5 0 0 0 0 0 0 0 0 0

3 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

void beolvas (vector<vector<double> > & mygraph, string filename)
{
ifstream input(filename);
stringstream ss;
char node[30];
char graph_size[2];

while(input.good()){

input.getline(graph_size,'\n');
cout << graph_size << endl;
ss << graph_size;
int graph_sizeINT = atoi(graph_size);
mygraph.resize(graph_sizeINT, vector<double>(graph_sizeINT,-1));
ss.clear();

for(int i=0; i<graph_sizeINT; i++)
{

input.getline(node,35,'\n');
//cout << node << endl;
ss << node;
for(int j= 0; j<graph_sizeINT; j++)
{
ss.getline(node,' ');
//cout << node << " ";
mygraph[i][j] = atof(node);
cout << mygraph[i][j] << " ";
}
cout << endl;
ss << "";
ss.clear();
}
} input.close(); }

感谢您的建议!

最佳答案

您正在使用 getlinestringstream,它们是很好的工具,但不是这项工作的正确工具;他们太强大了,需要太多照顾。与其确切地分析它们是如何出错的,不如看看当我们放弃它们以支持流输入时会发生什么:

void beolvas (vector<vector<double> > & mygraph, string filename)
{
ifstream input(filename.c_str());

int graph_sizeINT;
while(input >> graph_sizeINT)
{
cout << graph_sizeINT << endl;

mygraph.resize(graph_sizeINT, vector<double>(graph_sizeINT,-1));

for(int i=0; i<graph_sizeINT; i++)
{
char node[30];
for(int j= 0; j<graph_sizeINT; j++)
{
input >> mygraph[i][j];
cout << mygraph[i][j] << " ";
}
cout << endl;
}
}
input.close();
}

关于c++ - 从 stringstream 中提取到 2D vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27116201/

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