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

后端 未结 19 1071
梦毁少年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 03:09

    I know this question is really old but I think there's a better way of doing this

    #include 
    #include 
    
    bool string_to_int(std::string value, int * result) {
      std::stringstream stream1, stream2;
      std::string stringednumber;
      int tempnumber;
      stream1 << value;
      stream1 >> tempnumber;
      stream2 << tempnumber;
      stream2 >> stringednumber;
      if (!value.compare(stringednumber)) {
        *result = tempnumber;
        return true;
      }
      else return false;
    }
    

    If I wrote the code right, this will return a boolean value that tells you if the string was a valid number, if false, it wasn't a number, if true it was a number and that number is now result, you would call this this way:

    std::string input;
    std::cin >> input;
    bool worked = string_to_int(input, &result);
    

提交回复
热议问题