4

std::stringstreamからに書き込む最良の方法は何だろうと思っていvector<int>ます。

の内容の例を次に示しstringstreamます。 "31 #00 532 53 803 33 534 23 37"

これが私が持っているものです:

int buffer = 0;
vector<int> analogueReadings;
stringstream output;

 while(output >> buffer)
     analogueReadings.push_back(buffer);

しかし、何が起こっているように見えるかというと、それは最初のものを読み取り、次に取得し#00て戻ります0。これは数値ではないためです。

理想的には、私が望むのは、 a に#なり、次の空白まですべての文字をスキップすることです。これはフラグなどで可能ですか?

ありがとう。

4

4 に答える 4

6
#include <iostream>
#include <sstream>
#include <vector>

int main ( int, char ** )
{
    std::istringstream reader("31 #00 532 53 803 33 534 23 37");
    std::vector<int> numbers;
    do
    {
        // read as many numbers as possible.
        for (int number; reader >> number;) {
            numbers.push_back(number);
        }
        // consume and discard token from stream.
        if (reader.fail())
        {
            reader.clear();
            std::string token;
            reader >> token;
        }
    }
    while (!reader.eof());

    for (std::size_t i=0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << std::endl;
    }
}
于 2012-02-04T08:25:11.093 に答える
1

番号を取得したかどうかをテストする必要があります。ここからの答えを使用してください:

文字列がC++で数値かどうかを判断する方法は?

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

bool is_number(const std::string& s){
   std::string::const_iterator it = s.begin();
   while (it != s.end() && std::isdigit(*it)) ++it;
   return !s.empty() && it == s.end();
}
int main ()
{
    vector<int> analogueReadings;
    std::istringstream output("31 #00 532 04hello 099 53 803 33 534 23 37");

    std::string tmpbuff;
    while(output >> tmpbuff){
      if (is_number(tmpbuff)){
         int num;
         stringstream(tmpbuff)>>num;
         analogueReadings.push_back(num);
       }
    }
}

結果は 31 532 99 53 803 33 534 23 37 です。

また、このようなレキシカル キャストを使用することの 重要な欠点については、次のセクションで説明します: How to parse a string to an int in C++? の代替tringstream(tmpbuff)>>numが与えられます。

たとえば、04hello は 4 になり、7.4e55 は 7 になります。アンダーフローとアンダーフローにもひどい問題があります。André Caron によるクリーン ソリューションは、

25 10000000000 77 0 0

の中へ

25 0 0 

私のシステムで。77 も欠落していることに注意してください。

于 2012-02-04T08:12:03.573 に答える
0

ループなしバージョン:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <sstream>

using namespace std;

class IntegerFiller
{
    vector<int> &m_vec;
public:
    IntegerFiller(vector<int> &vec): m_vec(vec) {}

    void operator()(const std::string &str)
    {
        stringstream ss(str);
        int n;
        ss >> n;
        if ( !ss.fail() )
            m_vec.push_back(n);
    }
};

int main()
{
    vector<int> numbers;
    IntegerFiller filler(numbers);
    for_each(istream_iterator<string>(cin), istream_iterator<string>(), filler);
    copy(numbers.begin(), numbers.end(), ostream_iterator<int>(cout, " "));
    return 0;
}
于 2012-02-04T08:50:18.967 に答える