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

它的格式是:“字符串,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 :-)

谢谢

有帮助吗?

解决方案

这是一个有用的令牌化功能。它不使用流,但是可以通过在逗号上分配字符串来轻松执行所需的任务。然后,您可以使用由代币的生成向量进行任何您想做的事情。

/// 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() );
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top