问题
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.
Construct a std::istringstream from the line.
Keep reading numbers from the
std::istringstreamand add them to a std::vector. When you are done reading the contents of the line, the number of items in thestd::vectorgives 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;
}
来源:https://stackoverflow.com/questions/29133421/reading-double-matrix-from-cin