我得到了正在使用的代码。我需要接收来自命令行的输入并使用该输入。
例如,我可以输入:
a 3 b 2 b 1 a 1 a 4 b 2
它将给出输出:
1 3 4 1 2 2
我的问题是,我不能使用除大小为6(或12(之外的其他输入。
如果我使用输入
a 3 a 2 a 3
我会得到输出:
2 3 3 3
但应该得到:
2 3 3
如何在不遇到麻烦的情况下将未知大小作为输入?
我正试图解决以下问题:
读取数据集并按以下顺序将其写入cout:首先按数据集(先是a,然后是b(,然后按值。示例:输入:a 3 b 2 b 1 a 1 a 4 b 2输出:1 3 4 1 2 2
#include <iostream>
#include <math.h>
#include <algorithm>
#include <set>
#include <string>
#include <iterator>
#include <iomanip>
#include <vector>
using namespace std;
/*
input: a 3 b 2 b 1 a 1 a 4 b 2
output: 1 3 4 1 2 2
*/
//void insert_left
//void insert_right
//void Update
int main()
{
string my_vec_str;
double x;
vector<string> vect_string;
vector<int> vect_int;
bool go_on = true;
while (go_on)
{
cin >> my_vec_str;
cin >> x;
vect_string.push_back(my_vec_str);
vect_int.push_back(x);
if (cin.fail())
{
go_on = false;
}
if (vect_string.size() == 6 && vect_int.size() == 6)
{
go_on = false;
}
}
vector<int> vect_a;
vector<int> vect_b;
for (int i = 0; i < vect_string.size(); i++)
{
if (vect_string[i] == "a")
{
vect_a.push_back(vect_int[i]);
}
if (vect_string[i] == "b")
{
vect_b.push_back(vect_int[i]);
}
}
sort(vect_a.begin(), vect_a.end());
sort(vect_b.begin(), vect_b.end());
vector<int> vect_c;
for (int i = 0; i < vect_a.size(); i++)
{
vect_c.push_back(vect_a[i]);
}
for (int i = 0; i < vect_b.size(); i++)
{
vect_c.push_back(vect_b[i]);
}
for (auto &&i : vect_c)
{
cout << i << ' ';
}
return 0;
}
您可以使用std::getline
和std::stringstream
的组合来解析输入,这使您可以使用可变大小的输入而不必担心:
现场演示
#include <sstream>
//...
std::string my_vec_str;
char type; //to store type 'a' or 'b'
int value; //to store int value
std::vector<int> vect_a;
std::vector<int> vect_b;
std::getline(std::cin, my_vec_str); //parse the entirety of stdin
std::stringstream ss(my_vec_str); //convert it to a stringstream
while (ss >> type >> value) //parse type and value
{
if (type == 'a')
{
vect_a.push_back(value);
}
if (type == 'b')
vect_b.push_back(value);
}
//from here on it's the same
输入:
a 3 a 2 a 3
或者:
a 3 a 2 b 3 a b a //invalid inputs are not parsed
输出:
2 3 3
请注意,我没有使用using namespace std;
,这是有充分理由的。