从 cin 读取双矩阵

Reading double matrix from cin

我需要从 cin 读取小队矩阵,但我不知道这个矩阵的大小。所以我需要阅读第一行(用 space 或制表符分隔的双数,直到行尾)。解析此行后得到双数的计数。如果行中有 n 个双精度数,则矩阵大小将为 nxn。我怎样才能做到这一点?

代码:

unsigned int tempSize = 0;
double tempPoint;
double * tempArray = new double [0];
string ts;

getline(std::cin, ts);
std::istringstream s(ts);
while (s >> tempPoint){
    if (!s.good()){
        return 1;
    }
    tempArray = new double [tempSize+1];
    tempArray[tempSize] = tempPoint;
    tempSize++;
}
cout << "temp size " << tempSize << endl;

输出:

temp size 0
Program ended with exit code: 0
  1. 使用std::getline读取一行。

  2. 从行构造一个std::istringstream

  3. 继续读取 std::istringstream 中的数字并将它们添加到 std::vector 中。当您阅读完该行的内容后,std::vector 中的项数会给出矩阵的秩。

  4. 使用与读取矩阵第一行相同的逻辑来读取矩阵的其他行。

编辑

void readRow(std::vector<int>& row)
{
   std::string ts;
   std::getline(std::cin, ts);
   if ( std::cin )
   {
      std::istringstream s(ts);
      int item;
      while (s >> item){
         row.push_back(item);
      }
   }
   std::cout << "size " << numbers.size() << std::endl;
}