从cin中读取双矩阵

Reading double matrix from cin

本文关键字:读取 cin      更新时间:2023-10-16

我需要从cin中读取小队矩阵,但我不知道这个矩阵的大小。所以我需要读取第一行(用空格或制表符分隔的双数字,直到行尾)。在解析这一行以获得双数的计数之后。若行中有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;
}