从cin读取双矩阵 [英] Reading double matrix from cin

查看:194
本文介绍了从cin读取双矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从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;

输出:

 code> temp size 0 
程序以退出代码结束:0


解决方案


  1. 使用 std :: getline


  2. 构造一个 std :: istringstream 。 / p>


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


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

这篇关于从cin读取双矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆