[英]Reading double matrix from cin
我需要从cin读取小队矩阵,但我不知道此矩阵的大小。 因此,我需要阅读第一行(用空格或制表符分隔的双数字,直到行尾)。 解析此行以获取双数计数之后。 如果in row将是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
使用std::getline
读取一行。
从该行构造一个std::istringstream
。
继续从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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.