To change string to int

Asked 2 years ago, Updated 2 years ago, 117 views

How do I change string(char*) to int in C++? If the string is not a number, I would like to give an error in moderation rather than returning 0 (false).

c++ parsing

2022-09-22 14:58

1 Answers

C++11 is stoi, stol, stoll, Provides various functions, such as et="_blank">stoul.

int myNr = std::stoi(myString); Write with , and if you can't convert, then drop the exception.

However, this function returns the integer 11 when it transmits the string "11x", so if it is not this, please write another code.

const char* str = "123";
int i;

if(sscanf(str, "%d", &i)  == EOF )
{
   /* Error */
}
int str2int (const string &str) {
  stringstream ss(str);
  int num;
  if((ss >> num).fail())
  { 
      /* Error */
  }
  return num;
}
#include <boost/lexical_cast.hpp>
#include <string>

try
{
    std::string str = "123";
    int number = boost::lexical_cast< int >( str );
}
catch( const boost::bad_lexical_cast & )
{
    // // Error
}


2022-09-22 14:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.