字符串流到矢量<int>



我想知道从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,因为它不是一个数字。

理想情况下,我想要的是,它到达#,然后跳过所有字符,直到下一个空白。这可能有旗帜或其他东西吗?

谢谢。

#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;
    }
}

您需要测试是否得到了一个数字。使用这里的答案:

如何用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

此外,这里描述了使用这样的词法转换的重要缺点:如何在C++中将字符串解析为int,其中给出了CCD_ 8的替代方案。

例如,04hello变为4,7.4e55变为7。下溢和下溢也有可怕的问题。AndréCaron的清洁溶液转换

25 10000000000 77 0 0

进入

25 0 0 

在我的系统上。请注意,77也不见了!

无循环版本:

#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;
}

我认为最好的方法是

#include <string>
#include <sstream>
#include <vector>
using namespace std;   
int main()
{   
  string numbers = "23,24,27,28";   
  vector<int> integers;   
  stringstream s(numbers);   
  char ch;   
  int a;   
  while(s>>a>>ch) integers.push_back(a);   //s >> reads int char pair 
  s>>a;                                    // reads the last int
  integers.push_back(a); 
  for(int i = 0; i < integers.size(); i++) cout << integers[i] << "n";
}

最新更新