Search code examples
parsingc++11stringstream

Parsing a string into double and string in C++


I have a string like this

string myStr("123ab")

I'd like to parse it into

double d;
string str;

with d=123 and str=ab

I tried using string stream like this

istringstream ss(myStr);
ss >> d >> str;

But it didn't work. What's wrong?


Solution

  • The code in the OP worked as expected for me:

    #include <iostream>
    #include <sstream>
    #include <string>
    
    int main(int argc, char** argv) {
        for (int i = 1; i < argc; ++i) {
            std::istringstream ss(argv[i]);
            double d;
            std::string s;
            if (ss >> d >> s)
                std::cout << "In '" << argv[i]
                          << "', double is " << d
                          << " and string is '" << s << "'\n";
            else
                std::cout << "In '" << argv[i]
                          << "', conversion failed.\n";
        }
        return 0;
    }
    

    $ ./a.out 123ab
    In '123ab', double is 123 and string is 'ab'
    

    (Live on coliru.)


    However, it fails on input 123eb because the e is interpreted as an exponent indicator and there is no following exponent. There is no simple way around this issue with std::istringstream, which works somewhat like sscanf; fallback is not possible. However, std::strtod should find the longest valid floating point number, and therefore will be able to deal with 123eb. For example:

    #include <iostream>
    #include <sstream>
    #include <string>
    #include <cstring>
    
    int main(int argc, char** argv) {
        for (int i = 1; i < argc; ++i) {
            char* nptr;
            double d = strtod(argv[i], &nptr);
            if (nptr != argv[i]) {
                std::string s;
                if (std::istringstream(nptr) >> s) {
                    std::cout << "In '" << argv[i]
                              << "', double is " << d
                              << " and string is '" << s << "'\n";
                    continue;
                }
            }
            std::cout << "In '" << argv[i]
                      << "', conversion failed.\n";
        }
        return 0;
    }
    

    (Live on coliru.)