Converting c++ string to int

前端 未结 5 1624
天命终不由人
天命终不由人 2021-01-01 06:59

I have the following data in a c++ string

John Doe 01.01.1970

I need to extract the date and time from it into int variables. I tried it li

相关标签:
5条回答
  • 2021-01-01 07:09

    As far as I can tell, atoi does what you need.

    "Parses the C string str interpreting its content as an integral number, which is returned as an int value."

    http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

    0 讨论(0)
  • 2021-01-01 07:13

    Use streams to decode integers from a string:

    #include <iostream>
    #include <sstream>
    #include <string>
    
    int main()
    {
        std::string         x = "John Doe 02.01.1970";
    
        std::string         fname;
        std::string         lname;
        int                 day;
        int                 month;
        int                 year;
        char                sep;
    
        std::stringstream   data(x);
        data >> fname >> lname >> day >> sep >> month >> sep >> year;
    
        std::cout << "Day(" << day << ") Month(" << month << ") Year(" << year << ")\n";
    }
    

    The operator >> when used with a string variable will read a single (white) space separate word. When used with an integer variable will read an integer from the stream (discarding any proceeding (white) space).

    0 讨论(0)
  • 2021-01-01 07:13

    Try the Boost Data/Time library.

    0 讨论(0)
  • 2021-01-01 07:23

    Assuming (and that might be a bad assumption) that all the data was formatted similarly, I would do something like this

    char name[_MAX_NAME_LENTGH], last[_MAX_NAME_LENGTH];
    int month, day, year;
    
    sscanf( text_string, "%s %s %2d.%02d.%04d", first, last, &month, &day, &year );
    

    This does however, have the problem that the first/last names that appear in your input are only one word (i.e. this wouldn't work for things like "John M. Doe"). You would also need to define some appropriate maximum length for the string.

    It's hard to be more definitive about this solution unless we know more about the input.

    0 讨论(0)
  • 2021-01-01 07:29

    You need to use

    std::stringstream ss; 
    ss << stringVar;
    ss >> intVar;
    

    or

    intVar = boost::lexical_cast<int>(stringVar);.

    The later is a convenience wrapper from the boost library.

    0 讨论(0)
提交回复
热议问题