使用输入大小未知的 cin 从命令行获取 C++、字符串和整数

C++, strings and ints from command line using cin with unknown input size

我得到了正在使用的代码。我需要从命令行获取输入并使用该输入。

例如,我可以输入:

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 with std::stringstream 的组合来解析输入,这使您可以使用可变大小的输入而不必担心:

Live demo

#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;there are good reasons for that