How can I convert a std::string to int?

后端 未结 19 1082
梦毁少年i
梦毁少年i 2020-11-22 02:10

Just have a quick question. I\'ve looked around the internet quite a bit and I\'ve found a few solutions but none of them have worked yet. Looking at converting a string to

19条回答
  •  臣服心动
    2020-11-22 02:57

    To convert from string representation to integer value, we can use std::stringstream.

    if the value converted is out of range for integer data type, it returns INT_MIN or INT_MAX.

    Also if the string value can’t be represented as an valid int data type, then 0 is returned.

    #include 
    #include 
    #include 
    
    int main() {
    
        std::string x = "50";
        int y;
        std::istringstream(x) >> y;
        std::cout << y << '\n';
        return 0;
    }
    

    Output: 50

    As per the above output, we can see it converted from string numbers to integer number.

    Source and more at string to int c++

提交回复
热议问题