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

I have a variable like this:

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

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

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

How to do it? I know that I can overlay the line as follows:

iterations.c_str();

So, I tried c_int (), but this will not work:

iterations.c_int();
+3
source share
6 answers

You can use this:

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

See here for a description atoi.

+2
source

In order of preference:

boost::lexical_cast

atoi

std::stringstream

sscanf

Note that it lexical_castis simple enough to write 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;
}

he transforms anything into anything. (Credits: http://www.gotw.ca/publications/mill19.htm )

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

+8
source
int iters = atoi(str.c_str()); 

++, stringstream

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

int i;
ss >> i;
+1

zou - atoi (iterations.c_str());

+1
source

Do it:

istringstream ss(iterators);

int count;
ss >> count;

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

You can convert a 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;
}

To convert to an integer call as follows:

int output;

bool success = str2num( iterations, &output );
+1
source

Source: https://habr.com/ru/post/1781058/