【问题标题】:extract from stringstream into 2D vector从字符串流中提取到二维向量
【发布时间】:2015-01-22 20:03:53
【问题描述】:

这可能是一个愚蠢的问题,但无论如何: 我想从 .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();   }

感谢您的建议!

【问题讨论】:

    标签: c++ stl extract file-read atof


    【解决方案1】:

    您正在使用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();
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-02
      • 2021-11-18
      • 1970-01-01
      • 2013-01-10
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多