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

标签 c++ stl extract file-read atof

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

相关文章:

类中的 C++ 对象构造

c++ - (C++) 得到错误:类::函数的无效使用,我一点也不知道为什么

c++ - 在 C++ 代码中使用 new/delete 而不是 malloc/free 时崩溃

c++ - 如何在 stringstream 中放入一个字符串

c++ - Boost - unordered_set 教程/示例/任何东西?

python pandas 用空格将字符串列分成两部分

c++ - C++ 上限函数的奇怪结果

c++ - const 容器是否只有 const 迭代器?

c - 如何提取字符串中的数据?

r - 从 r 中的数字中提取数字