0

I have string like "y.x-name', where y and x are number ranging from 0 to 100. From this string, what would be the best method to extract 'x' into an integer variable in C++.

0

4 Answers 4

1

You could split the string by . and convert it to integer type directly. The second number in while loop is the one you want, see sample code:

template<typename T>
T stringToDecimal(const string& s)
{
    T t = T();
    std::stringstream ss(s);
    ss >> t;
    return t;
}

int func()
{     
    string s("100.3-name");

    std::vector<int> v;
    std::stringstream ss(s);
    string line;

    while(std::getline(ss, line, '.'))
    {
         v.push_back(stringToDecimal<int>(line));
    }

    std::cout << v.back() << std::endl;

}

It will output: 3

Sign up to request clarification or add additional context in comments.

2 Comments

@ billz: could you please explain ss >> t ?
ss>>t convert string(which can be 100 or 3-name) to t, it only writes integer type and cut off unrelated string. just like atoi function. see en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
0

It seem that this thread has a problem similar to you, it might help ;)

Simple string parsing with C++

Comments

0

You can achieve it with boost::lexical_cast, which utilizes streams like in billz' answer: Pseudo code would look like this (indices might be wrong in that example):

std::string yxString = "56.74-name";
size_t xStart = yxString.find(".") + 1;
size_t xLength = yxString.find("-") - xStart;
int x = boost::lexical_cast<int>( yxString + xStart, xLength );

Parsing errors can be handled via exceptions that are thrown by lexical_cast. For more flexible / powerful text matching I suggest boost::regex.

Comments

0

Use two calls to unsigned long strtoul( const char *str, char **str_end, int base ), e.g:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(){

    char const * s = "1.99-name";
    char *endp;
    unsigned long l1 = strtoul(s,&endp,10);
    if (endp == s || *endp != '.') {
        cerr << "Bad parse" << endl;
        return EXIT_FAILURE;
    }
    s = endp + 1;
    unsigned long l2 = strtoul(s,&endp,10);
    if (endp == s || *endp != '-') {
        cerr << "Bad parse" << endl;
        return EXIT_FAILURE;
    }
    cout << "num 1 = " << l1 << "; num 2 = " << l2 << endl;
    return EXIT_FAILURE;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.