質問
この文字列を使用してどのように解析できるのかを理解しようとしています。sstream
「そしてC ++
それの形式は「string、int、int」です。
文字列の最初の部分をSTD :: stringに含む文字列の最初の部分を割り当てることができる必要があります。
この文字列の例は次のとおりです。
std::string("127.0.0.1,12,324");
その後、入手する必要があります
string someString = "127.0.0.1";
int aNumber = 12;
int bNumber = 324;
使用できないことをもう一度述べます boost
図書館、ちょうど sstream
:-)
ありがとう
解決
これが有用なトークン化関数です。ストリームは使用しませんが、コンマに文字列を分割することで、必要なタスクを簡単に実行できます。その後、結果のトークンのベクトルでやりたいことは何でもできます。
/// String tokenizer.
///
/// A simple tokenizer - extracts a vector of tokens from a
/// string, delimited by any character in delims.
///
vector<string> tokenize(const string& str, const string& delims)
{
string::size_type start_index, end_index;
vector<string> ret;
// Skip leading delimiters, to get to the first token
start_index = str.find_first_not_of(delims);
// While found a beginning of a new token
//
while (start_index != string::npos)
{
// Find the end of this token
end_index = str.find_first_of(delims, start_index);
// If this is the end of the string
if (end_index == string::npos)
end_index = str.length();
ret.push_back(str.substr(start_index, end_index - start_index));
// Find beginning of the next token
start_index = str.find_first_not_of(delims, end_index);
}
return ret;
}
他のヒント
C ++文字列ツールキットライブラリ(STRTK) あなたの問題に対する次の解決策があります:
int main() { std::string data("127.0.0.1,12,324"); string someString; int aNumber; int bNumber; strtk::parse(data,",",someString,aNumber,bNumber); return 0; }
より多くの例を見つけることができます ここ
空想ではありませんが、std :: getlineを使用して文字列を分割できます。
std::string example("127.0.0.1,12,324");
std::string temp;
std::vector<std::string> tokens;
std::istringstream buffer(example);
while (std::getline(buffer, temp, ','))
{
tokens.push_back(temp);
}
次に、分離された各文字列から必要な情報を抽出できます。
あなたもこのようなことをすることができます(私の頭の上から完全に外れているので、私がそこにいくつかの間違いを犯した場合、謝罪します)...
stringstream myStringStream( "127.0.0.1,12,324" );
int ipa, ipb, ipc, ipd;
char ch;
int aNumber;
int bNumber;
myStringStream >> ipa >> ch >> ipb >> ch >> ipc >> ch >> ipd >> ch >> aNumber >> ch >> bNumber;
stringstream someStringStream;
someStringStream << ipa << "." << ipb << "." << ipc << "." << ipd;
string someString( someStringStream.str() );
所属していません StackOverflow