12

我试图弄清楚如何使用“ sstream”和 C++解析这个字符串

它的格式是:“string,int,int”。

我需要能够将包含 IP 地址的字符串的第一部分分配给 std::string。

这是此字符串的示例:

std::string("127.0.0.1,12,324");

然后我需要获得

string someString = "127.0.0.1";
int aNumber = 12;
int bNumber = 324;

我会再次提到我不能使用boost图书馆,只是sstream:-)

谢谢

4

4 回答 4

13

C++ 字符串工具包库(Strtk)为您的问题提供了以下解决方案:

主函数()
{
   标准::字符串数据(“127.0.0.1,12,324”);
   字符串 someString;
   一个整数;
   整数 bNumber;
   strtk::parse(data,",",someString,aNumber,bNumber);
   返回0;
}

更多示例可以在这里找到

于 2010-01-15T19:24:58.087 回答
6

这并不花哨,但您可以使用 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);
}

然后,您可以从每个分离的字符串中提取必要的信息。

于 2010-01-15T16:33:28.333 回答
3

这是一个有用的标记化功能。它不使用流,但可以通过用逗号分隔字符串来轻松执行您需要的任务。然后你可以对生成的标记向量做任何你想做的事情。

/// 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;
}
于 2010-01-15T16:26:07.487 回答
2

我相信你也可以做这样的事情(完全不在我的脑海中,如果我在那里犯了一些错误,我深表歉意)......

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() );
于 2010-01-15T16:30:12.597 回答