【发布时间】:2016-04-29 06:46:41
【问题描述】:
我正在编写使用 STL 向量创建矩阵类的代码。我希望用户输入(在控制台上)为:
1 2 3
4 5 6
或
1 2 3
4 5 6
7 8 9
仅此而已。即代码应该能够从输入本身获取行数和列数(而不是显式询问用户)。
有人可以指导我吗?
【问题讨论】:
-
请分享您到目前为止所尝试的内容。
-
只是好奇,为什么投反对票?
我正在编写使用 STL 向量创建矩阵类的代码。我希望用户输入(在控制台上)为:
1 2 3
4 5 6
或
1 2 3
4 5 6
7 8 9
仅此而已。即代码应该能够从输入本身获取行数和列数(而不是显式询问用户)。
有人可以指导我吗?
【问题讨论】:
我会一次读取一行输入,直到一行为空。
#include<iostream>
#include<string>
using namespace std;
int main(){
string s,s1;
do{
getline (std::cin, s);
s1+=s;
}while(s.length()>0);
cout<<s1;
return 0;
}
您需要编写一个简单的函数来将字符串 s 拆分为数字,而不是添加到 s1,在第一步存储列数,测试列数是否改变(抛出错误),增加每一步的行数,当然,将矩阵的元素存储在向量中。完成后,就可以构造矩阵了
【讨论】:
好的.. 我找到了一种方法。谢谢安德烈.. 这是我的做法..
#include<iostream>
#include<vector>
#include<string>
#include <sstream>
#include <iterator>
using namespace std;
int main() {
vector <vector <double> > v;
string s;
int count=0, ncol=0,check=0,nrow=0;
while(1) {
getline(cin,s);
if (s.length() == 0)
break;
for (int i=0; i<s.length(); i++)
if (s[i]==' ')
count++;
count++;
if (check==0) {
check++;
ncol=count;
}
if (count != ncol) {
cout << "ncol should be same in each row!" <<endl;
break;
}
v.resize(nrow+1);
istringstream buf(s);
istream_iterator<string> beg(buf), end;
vector<string> dummy(beg, end);
for (int i=0; i<ncol;i++)
v[nrow].push_back(stod(dummy[i]));
nrow++;
count=0;
}
//print the vector 'v' here
}
【讨论】: