Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to long

Tags:

c++

string

I'm trying to convert a string to long. It sounds easy, but I still get the same error. I tried:

include <iostream>
include <string>    

using namespace std;

int main()
{
  string myString = "";
  cin >> myString;
  long myLong = atol(myString);
}

But always the error:

.../main.cpp:12: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'long int atol(const char*)'

occured. The reference says following:

long int atol ( const char * str );

Any help?

like image 249
PEAR Avatar asked Mar 29 '14 15:03

PEAR


1 Answers

Try

long myLong = std::stol( myString );

The function has three parameters

long stol(const string& str, size_t *idx = 0, int base = 10);

You can use the second parameter that to determine the position in the string where parsing of the number was stoped. For example

std::string s( "123a" );

size_t n;

std::stol( s, &n );

std::cout << n << std::endl;

The output is

3

The function can throw exceptions.

like image 196
Vlad from Moscow Avatar answered Oct 21 '22 03:10

Vlad from Moscow