-1

I am working in c++. I have a string that contains the following number

std::string s= "8133522648";

I want to convert this number in

long long int nr;

I did: nr=atoll(s.c_str()). The result is: -456410944. How to solve this error? Thanks

Edit:

In fact I have:

const char* str="8133523648";
I have to convert it into long long int nr=8133523648

Thanks for help! Appreciate!

Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
sunset
  • 1,359
  • 5
  • 22
  • 35

3 Answers3

4

use int64_t instead of long long. which is defined in stdint.h

If you rely on boost you can use

std::string s= "8133522648";
int64_t nr = boost::lexical_cast<int64_t, std::string>(s);
Mythli
  • 5,995
  • 2
  • 24
  • 31
  • Doesn't make a difference - all standards that define `int64_t` also define `long long` as a >= 64 bit type. – MSalters Aug 02 '11 at 11:07
  • stdint.h will probably work on most compilers but is no C++ standard. – KillianDS Aug 02 '11 at 11:08
  • Good to know. My c++ book is just saying that i should better use int64_t, uint32_t... – Mythli Aug 02 '11 at 11:10
  • 1
    @Mythli: Then see the [Definitive c++ book guide and list](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – MSalters Aug 02 '11 at 11:19
3

It can be done in better way as follows:

#include <sstream>

stringstream sstr;
sstr << "8133522648";

long long nr;
sstr >> nr;

Don't use atoll() as it is not defined by C++ standard. Some compiler may implement it while others don't. Also,

std::string s = 8133522648;

doesn't mean

std::string s = "8133522648";

which was probably what you wanted.

Donotalo
  • 12,748
  • 25
  • 83
  • 121
  • atoll is in C standard, so when he includes it will be working.. Every compiler will be working.. Question is that he has library.. – nirmus Aug 02 '11 at 10:49
  • 2
    @nirmus: the question is tagged C++, and neither `atoll` nor `long long` are defined in C++03. However, you can probably assume that most compilers that support `long long` also support `atoll`. – Mike Seymour Aug 02 '11 at 10:51
  • @mike: i didn't know `long long` isn't defined by C++03. :( – Donotalo Aug 02 '11 at 11:00
  • i am working in ubuntu and i compile with g++. I ve edited my question. need help – sunset Aug 02 '11 at 11:04
  • @Donotalo: It's in C++11, which modern compilers are currently implementing. So there's no real surpise if it works. – MSalters Aug 02 '11 at 11:05
  • @msalter: yep. actually i've been using `long long` type for so long that i've forgotten it hasn't been standardized. – Donotalo Aug 02 '11 at 11:09
0

Below code is working fine:

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>

    using namespace std;

    int main() {

       std::string s= "8133522648";
       long long int nr = atoll(s.c_str());
       cout << nr;
    }
nirmus
  • 4,913
  • 9
  • 31
  • 50