-1

「5812 458137」などのファイルから入力行を読み込んでいます。

これらの整数を直接配列に入れることはできますか、それとも最初に文字列に入れる必要がありますか?

最初に文字列を使用する必要がある場合、この整数の文字列を配列に変換するにはどうすればよいですか?

入力: "5 8 12 45 8 13 7" =>そのような配列に:{5,8,12,45,8,13,7}

4

1 に答える 1

7

いいえ、文字列に変換する必要はありません。C++ 標準ライブラリのコンテナーとアルゴリズムを使用すると、実際には非常に簡単です (区切り文字が空白または一連の空白である限り、これは機能します)。

#include <iterator>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v;

    // An easy way to read a vector of integers from the standard input
    std::copy(
        std::istream_iterator<int>(std::cin), 
        std::istream_iterator<int>(), 
        std::back_inserter(v)
        );

    // An easy wait to print the vector to the standard output
    std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
}
于 2013-02-06T22:04:32.143 に答える