0

私のプログラムは次のような行をとります: 1, 5, 6, 7 次に、各整数を配列に格納します。

最初は入力は文字列として受け取るべきだと思います。しかし、これをコンマとスペース区切りでどのように分割できますか? 次に、整数として配列に格納する方法は?

4

2 に答える 2

5

std::string::find分割には、 とを使用できますstd::string::substr。たとえば、ループで呼び出しstr.find(", ")て、文字列を で分割しますsubstr

ストレージには配列を使用しないでください。使用する必要がありますstd::vector

部分文字列を整数に変換するには、eg を参照してくださいstd::stoi

于 2012-10-05T10:31:16.477 に答える
1

Joachimの回答に加えて(そして、あなたの質問が誤って C++11 とタグ付けされていなかったことを考えると)、最も一般的なアプローチはおそらく正規表現を使用することです。

#include <regex>
#include <vector>
#include <algorithm>
#include <iterator>

std::vector<int> parse(const std::string &str)
{
    //is it a comma-separated list of positive or negative integers?
    static const std::regex valid("(\\s*[+-]?\\d+\\s*(,|$))*");
    if(!std::regex_match(str, valid))
        throw std::invalid_argument("expected comma-separated list of ints");

    //now just get me the integers
    static const std::regex number("[+-]?\\d+");
    std::vector<int> vec;
    std::transform(std::sregex_iterator(str.begin(), str.end(), number), 
                   std::sregex_iterator(), std::back_inserter(vec), 
                   [](const std::smatch &m) { return std::stoi(m.str()); });
    return vec;
}

たとえば、正の数のみが必要な場合、各コンマの後に単一のスペースのみが必要な場合、またはコンマの前にスペースが必要ない場合など、ニーズに合わせて調整できますが、全体的なアプローチは明確でなければなりません。しかし、これはあなたの特定のニーズにはやり過ぎかもしれません. Joachimの手動解析のアプローチの方が適しているかもしれません.

于 2012-10-05T11:24:08.340 に答える