Question

I have a string which actually contains a number and a string, separated by ,, for instance "12,fooBar".

I would like to put it into separated variables, i.e. the number into unsigned int myNum and the string into std::string myStr.

I have the following snipped of code:

size_t pos1=value.find(',');
std::cout << value.substr(0, pos1) << " and " 
          << (value.substr(0, pos1)).c_str() << std::endl;

This yields 12 and 1. Anything I missed here? What happend to the 2 in the second part?

Note: I isolated the problem to this snipped of code. I need c_str() to pass it to atoi to get the unsigend int. Here I don't want to print the second part.

Update: I actually get the string from levelDB Get. If I put a test string like I put here, it works.

Was it helpful?

Solution

The posted code produces the same substring: value.substr(0, pos1). Note that std::string::substr() does not modify the object, but returns a new std::string.

Example:

#include <iostream>
#include <string>

int main ()
{
    std::string value ="12,fooBar";
    unsigned int myNum;
    std::string myStr;

    const size_t pos1 = value.find(',');    
    if (std::string::npos != pos1)
    {
        myNum = atoi(value.substr(0, pos1).c_str());
        myStr = value.substr(pos1 + 1);
    }

    std::cout << myNum << " and " 
              << myStr << std::endl;

    return 0;
}

Output:

12 and fooBar

EDIT:

If the unsigned int is the only piece required then the following will work:

unsigned int myNum = atoi(value.c_str());

as atoi() will stop at the first non-digit character (excluding optional leading - or +), in this case the ,.

OTHER TIPS

The cleanest C++ style solution to this problem is to use a stringstream.

#include <sstream>
// ...
std::string value = "12,fooBar";
unsigned int myNum;
std::string myStr;
std::stringstream myStream(value);
myStream >> myNum;
myStream.ignore();
myStream >> myStr;

Your second substr should be value.substr(pos1+1,value.length())

One more option is using std::from_chars function from the 17th standard (< charconv > header):

int x;
from_chars(&s[i], &s.back(), x); // starting from character at index i parse
                                // the nearest interger till the second char pointer

There are different overloads for different types of value x (double etc.).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top