从cin读取双矩阵 [英] Reading double matrix from 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
-
使用
std :: getline
。 -
构造一个
std :: istringstream
。 / p> -
继续阅读
std :: istringstream
中的数字,并将它们添加到std :: vector
。当您完成阅读该行的内容后,std :: vector
中的项目数量将提供矩阵的排名。 -
使用与读取矩阵第一行相同的逻辑来读取矩阵的其他行。
编辑
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
Read a line using
std::getline
.Construct a
std::istringstream
from the line.Keep reading numbers from the
std::istringstream
and add them to astd::vector
. When you are done reading the contents of the line, the number of items in thestd::vector
gives you the rank of the matrix.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屋!