Closed lifeisamovie closed 9 years ago
@lifeisamoive
Did you mean:
int i, j;
while ( cin >> i >> j ) {
vec1.push_back(i);
vec2.push_back(j);
}
:walking:
Not really,I want to read a sequence of ints into one vector completely after another.Just like this, 1 2 3 4 //vec1,一次输入1 2 3 4,到vec1 5 6 7 8//vec2,第二次输入5 6 7 8,到vec2, how can I do that?
all right,my English is not that good. Thanks a lot.
@lifeisamoive
这本来就是中文讨论区,直接说中文就好。
我明白你的意思了,但如何区分两次输入呢?每一次输入的数字个数固定(如 4)?还是弄个标记说明第一次输入完毕,如(#, -1 之类的特殊字符或数字)?
恩,我是想一次输入不确定长度的ints到一个vector,然后再输一串数字到另一个vector,你说的“弄个标记说明第一次输入完毕”挺好的
@lifeisamoive
没问题的,可以一行一行的来,一行就对应一个 vector
,这也省了标记了。
#include <iostream>
using std::cout; using std::cin; using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <sstream>
int main()
{
vector<vector<int>> vecGroup(2);
size_t index = 0;
for (string line; std::getline(cin, line); ++index) {
std::istringstream iss(line);
for (int n; iss >> n; )
vecGroup.at(index).push_back(n);
if ( vecGroup.size() - 1 == index ) break;
}
// output
for (size_t i = 0; i != vecGroup.size(); ++i) {
cout << "vec" << i << ": ";
for (auto n : vecGroup.at(i))
cout << n << " ";
cout << endl;
}
}
测试如下:
// 输入:
1 2 3 4 5 6 7
8 9 10
// 输出:
vec0: 1 2 3 4 5 6 7
vec1: 8 9 10
How can I read a sequence of ints from cin and store the values two vectors at the same time?like this, vector val1,val2;
int i,j;
while(cin>>i) val1.push_back(i);
while(cin>>j) val2.push_back(j);