简体   繁体   中英

How to cast const std::string& to integer?

I have a variable like this:

const std::string& iterations = "30";

I want to use it to determine number of iterations for a "for" loop:

for ( int i = 0; i < iterations; i++ ) {
  // do something
}

How to do that? I know I can cast to string like this:

iterations.c_str();

So I tried c_int() but it won't work:

iterations.c_int();

In order of preference:

boost::lexical_cast

atoi

std::stringstream

sscanf

Note that lexical_cast is simple enough to be written here:

#include <exception>
#include <sstream>

struct bad_lexical_cast : std::exception {};

template<typename Target, typename Source>
Target lexical_cast(Source arg)
{
  std::stringstream interpreter;
  Target result;
  if(!(interpreter << arg) ||
     !(interpreter >> result) ||
     !(interpreter >> std::ws).eof())
    throw bad_lexical_cast();
  return result;
}

it converts anything into anything. (Credits: http://www.gotw.ca/publications/mill19.htm )

Usage : int iter = lexical_cast<int>(iterations)

You could use this:

int foo = atoi( iterators.c_str() );

See here for a description of atoi .

int iters = atoi(str.c_str()); 

You can also use a more modern, C++ style method by utilizing a stringstream

string s = "1234";
stringstream ss(s); 

int i;
ss >> i;

你只需要使用简单的函数 - atoi(iterations.c_str());

Do this:

istringstream ss(iterators);

int count;
ss >> count;

for ( int i = 0; i < count; i++ ) {
  // do something
}

You can convert the string to a number using the following function:

#include <sstream>
#include <string>
#include <ios>

template<class T>
bool str2num( const std::string& s, T *pNumber, 
              std::ios_base::fmtflags fmtfl = std::ios_base::dec )
{
  std::istringstream  stm( s.c_str() );

  stm.flags( fmtfl );
  stm >> (*pNumber);
  return stm.fail() == false;
}

For converting to an integer call as follows:

int output;

bool success = str2num( iterations, &output );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM