【发布时间】:2021-01-20 16:51:29
【问题描述】:
我得到了正在使用的代码。我需要从命令行获取输入并使用该输入。
例如,我可以输入:
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;
}
【问题讨论】:
-
发送最后一条数据后会发生什么?您是否发送类似“END”或 eof 或关闭
cin的内容? -
不,这就是问题所在。我不知道如何在不自己做的情况下结束while循环。
-
这不能解决问题,但不需要
vect_c。就用两个循环,一个写vect_a的内容,一个写vect_b的内容。 -
啊,好点子!谢谢!我也不知道如何使用“END”或 eof。我不确定如何感知何时可以让计算机知道最后一条数据何时发送。
标签: c++ string vector integer cin