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

前端 未结 17 1761
忘了有多久
忘了有多久 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条回答
  •  Happy的楠姐
    2020-11-21 11:52

    You could use this defined method.

    #define toInt(x) {atoi(x.c_str())};
    

    And if you were to convert from String to an Integer, you would just do the following.

    int main()
    {
    string test = "46", test2 = "56";
    int a = toInt(test);
    int b = toInt(test2);
    cout<

    The output would be 102.

提交回复
热议问题