番号を取得したかどうかをテストする必要があります。ここからの答えを使用してください:
文字列が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 も欠落していることに注意してください。