之前做一些笔试题碰到矩阵元素输入不知道行列数的情况,没法事先设定矩阵的大小及简单使用for循环嵌套输入,这边可以使用c++中的getline()语句,按行读入,然后根据空格分割元素。
getline(cin, str, '#'); //遇到‘#’停止读入,默认为‘\n’
我们首先将每行以string的格式读入,然后以空格为标志将分隔的字符转换为int整数类型,放入vector数组中。
完整的代码如下所示
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(){
vector<int> input;
string temp;
vector<vector<int>> matrix;
while ((getline(cin, temp))&&temp!=""){
for (int i=0;i<temp.size();++i){
int num=0;
while (temp[i]!=' '&&temp[i]!='\0'){
num=num*10+(temp[i]-'0');
++i;
}
input.push_back(num);
}
matrix.push_back(input);
input.clear(); //每次循环需要将input数组清空
}
cout << "matrix:"<<endl;
for (int i=0;i<matrix.size();++i){
for (int j=0;j<matrix[i].size();++j){
cout<<matrix[i][j]<<' ';
}
cout<<endl;
}
return 0;
}
这边特别需要注意的是跳出循环的条件,如果只是while (getline(cin, temp)),判断的是cin是否成功,只要有输入(包括回车)一定为true,所以可以加上&&temp!="",当读取的行为空时就跳出循环。