-6

Okay So i have this function

long  valid(const char* str)    
{
    int temp = atoi(str)
    return long;
}

`str = 9789070002046`  //13 digit long

the function returns some random 10 digit number.I have also tried STOI stringstream

Shivam Gupta
  • 77
  • 1
  • 8
  • 4
    `return long; ` ?? Um. clearly not your *real* code. And how do you know that number is even representable as a `long` ? If `long` is 32-bit (maximum signed value of `2147483647`), it won't fit. – WhozCraig Jan 26 '15 at 02:24
  • 1
    You are likely looking for `std::stol` or `std::stoll`, Or perhaps `strtol` and `strtoll`, if you insist on using C-style strings. – Igor Tandetnik Jan 26 '15 at 02:27
  • I would recommend to use size_t or ptrdiff_t to match the pointer length of your architecture. – moo Jan 26 '15 at 02:41
  • possible duplicate of [How to convert a number to string and vice versa in C++](http://stackoverflow.com/questions/5290089/how-to-convert-a-number-to-string-and-vice-versa-in-c) – IllusiveBrian Jan 26 '15 at 02:49

1 Answers1

0

@shivam-gupta hi buddy,

You maybe have been quite new to C/C++ programming is that correct? Some people at the forum require you to make explain what your problem is in detail also with the right C++ syntax.

I know what you mean, and it had been a main problem with me in the beginning when I tried to learn C/C++. The function that you might be looking at is atol() not atoi(). From my point of view it is better to convert the string to double, then cast it to a long/integer variable.

The code I used to complete your snippet is this

#include <iostream>

long valid(const char* str);

int main()
{
    long test;
    const char *str = "9789070002046";  //13 digit long

    test = valid(str);

    std::cout << test << " sizeof test is " << sizeof(test) << std::endl;

    return 0;
}

long valid(const char* str)
{
    long temp = (long)atol(str);
    return temp;
}

Enjoy coding C++! And remember, life is not too short to learn C++!

Dendi Suhubdy
  • 2,877
  • 3
  • 19
  • 20