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

前端 未结 17 2190
忘了有多久
忘了有多久 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 11:41

    You can use the a stringstream from the C++ standard libraray:

    stringstream ss(str);
    int x;
    ss >> x;
    
    if(ss) { // <-- error handling
      // use x
    } else {
      // not a number
    }
    

    The stream state will be set to fail if a non-digit is encountered when trying to read an integer.

    See Stream pitfalls for pitfalls of errorhandling and streams in C++.

提交回复
热议问题