문제

"이 문자열을 어떻게 구문 분석 할 수 있는지 알아 내려고 노력하고 있습니다.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 :-)

감사

도움이 되었습니까?

해결책

다음은 유용한 토큰 화 기능입니다. 스트림을 사용하지 않지만 쉼표에서 문자열을 분할하여 필요한 작업을 쉽게 수행 할 수 있습니다. 그런 다음 결과적인 토큰 벡터로 원하는대로 할 수 있습니다.

/// 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