簡體   English   中英

來自命令行的 C++、字符串和整數,使用未知輸入大小的 cin

[英]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::getlinestd::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; 這有充分的理由

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM