How to parse a string to an int in C++?

前端 未结 17 1728
忘了有多久
忘了有多久 2020-11-21 11:01

What\'s the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).

17条回答
  •  逝去的感伤
    2020-11-21 12:02

    I know three ways of converting String into int:

    Either use stoi(String to int) function or just go with Stringstream, the third way to go individual conversion, Code is below:

    1st Method

    std::string s1 = "4533";
    std::string s2 = "3.010101";
    std::string s3 = "31337 with some string";
    
    int myint1 = std::stoi(s1);
    int myint2 = std::stoi(s2);
    int myint3 = std::stoi(s3);
    
    std::cout <<  s1 <<"=" << myint1 << '\n';
    std::cout <<  s2 <<"=" << myint2 << '\n';
    std::cout <<  s3 <<"=" << myint3 << '\n';
    

    2nd Method

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    
    int StringToInteger(string NumberAsString)
    {
        int NumberAsInteger;
        stringstream ss;
        ss << NumberAsString;
        ss >> NumberAsInteger;
        return NumberAsInteger;
    }
    int main()
    {
        string NumberAsString;
        cin >> NumberAsString;
        cout << StringToInteger(NumberAsString) << endl;
        return 0;
    } 
    

    3rd Method - but not for an individual conversion

    std::string str4 = "453";
    int i = 0, in=0; // 453 as on
    for ( i = 0; i < str4.length(); i++)
    {
    
        in = str4[i];
        cout <

提交回复
热议问题