Reading double matrix from cin

假如想象 提交于 2019-12-11 20:21:14

问题


I need to read squad matrix from cin, but I don't know the size of this matrix. So I need to read first row(double numbers separated by space or tab till end of line). After parse this line to get count of double numbers. If in row will be n double numbers then matrix size will nxn. How can I do that?

Code:

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;

Output:

temp size 0
Program ended with exit code: 0

回答1:


  1. Read a line using std::getline.

  2. Construct a std::istringstream from the line.

  3. Keep reading numbers from the std::istringstream and add them to a std::vector. When you are done reading the contents of the line, the number of items in the std::vector gives you the rank of the matrix.

  4. Use the same logic that was used to read the first row of the matrix to read the other rows of the matrix.

EDIT

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;
}


来源:https://stackoverflow.com/questions/29133421/reading-double-matrix-from-cin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!