这可能是一个愚蠢的问题,但无论如何: 我想从.txt文件中获取数字,该文件包含图形的邻接矩阵,文件的第一行只包含节点数。
10
-1 5 3 -1 -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(); }
感谢您的任何建议!
答案 0 :(得分:0)
您使用的是getline
和stringstream
,它们是很好的工具,但却不适合这项工作;它们太强大了,需要太多关心。而不是准确地分析它们是如何出错的,看看当我们放弃它们时会发生什么,支持流输入:
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();
}