Solved

Convert String to Integer

Posted on 2004-10-07
5
94,348 Views
Last Modified: 2011-08-18
How can I convert a standard string to an integer?
0
Comment
Question by:rossryan
  • 2
  • 2
5 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 12251838
There are several methods, the easiest being 'atoi()' the most flexible IMHO (in terms of error checking) being 'strtol()':


/* ATOF.C: This program shows how numbers stored
 * as strings can be converted to numeric values
 * using the atof, atoi, and atol functions.
 */

#include <stdlib.h>
#include <stdio.h>

void main( void )
{
   char *s; double x; int i; long l;

   s = "  -2309.12E-15";    /* Test of atof */
   x = atof( s );
   printf( "atof test: ASCII string: %s\tfloat:  %e\n", s, x );

   s = "7.8912654773d210";  /* Test of atof */
   x = atof( s );
   printf( "atof test: ASCII string: %s\tfloat:  %e\n", s, x );

   s = "  -9885 pigs";      /* Test of atoi */
   i = atoi( s );
   printf( "atoi test: ASCII string: %s\t\tinteger: %d\n", s, i );

   s = "98854 dollars";     /* Test of atol */
   l = atol( s );
   printf( "atol test: ASCII string: %s\t\tlong: %ld\n", s, l );
}

Output

atof test: ASCII string:   -2309.12E-15   float:  -2.309120e-012
atof test: ASCII string: 7.8912654773d210   float:  7.891265e+210
atoi test: ASCII string:   -9885 pigs      integer: -9885
atol test: ASCII string: 98854 dollars      long: 98854

/* STRTOD.C: This program uses strtod to convert a
 * string to a double-precision value; strtol to
 * convert a string to long integer values; and strtoul
 * to convert a string to unsigned long-integer values.
 */

#include <stdlib.h>
#include <stdio.h>

void main( void )
{
   char   *string, *stopstring;
   double x;
   long   l;
   int    base;
   unsigned long ul;
   string = "3.1415926This stopped it";
   x = strtod( string, &stopstring );
   printf( "string = %s\n", string );
   printf("   strtod = %f\n", x );
   printf("   Stopped scan at: %s\n\n", stopstring );
   string = "-10110134932This stopped it";
   l = strtol( string, &stopstring, 10 );
   printf( "string = %s", string );
   printf("   strtol = %ld", l );
   printf("   Stopped scan at: %s", stopstring );
   string = "10110134932";
   printf( "string = %s\n", string );
   /* Convert string using base 2, 4, and 8: */
   for( base = 2; base <= 8; base *= 2 )
   {
      /* Convert the string: */
      ul = strtoul( string, &stopstring, base );
      printf( "   strtol = %ld (base %d)\n", ul, base );
      printf( "   Stopped scan at: %s\n", stopstring );
   }
}


Output

string = 3.1415926This stopped it
   strtod = 3.141593
   Stopped scan at: This stopped it

string = -10110134932This stopped it   strtol = -2147483647   Stopped scan at: This stopped itstring = 10110134932
   strtol = 45 (base 2)
   Stopped scan at: 34932
   strtol = 4423 (base 4)
   Stopped scan at: 4932
   strtol = 2134108 (base 8)
   Stopped scan at: 932

0
 
LVL 86

Accepted Solution

by:
jkr earned 200 total points
ID: 12251980
BTW, regarding the 'std::string' issue - all you have to do is calling the 'c_str()' member of that class before passing it to any of these functions, e.g.

std::string str = "1234";

int i;

i = atoi(str.c_str());

char* pc;

i = (int) strtol(str.c_str(), &pc, 10);

if ( NULL != *pc) {

    // conversion error, probably incorrect numerical format
}
0
 
LVL 17

Assisted Solution

by:rstaveley
rstaveley earned 50 total points
ID: 12254080
Arguably, the most C++-ish way to do it is using std::istringstream:
--------8<--------
#include <iostream>
#include <sstream>

int main()
{
      std::istringstream istr("1234");
      int i;
      istr >> i;
      std::cout << "Value is " << i << '\n';
}
--------8<--------
0
 

Expert Comment

by:poojasureshkumar
ID: 14893408
Hi.
I want to convert string "&H0" into long variable.Can any one help me?
I tried with long.parse(string) and Convert.ToInt64(string)..which will not work because the string argument must contain numneric string value.

Can any one help me .

Advance Thanks,
suresh
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 14893586
You are in the wrong place, suresh, I think you want http:/Programming/Programming_Languages/Dot_Net/VisualC_PLUS_PLUS_DOT_NET/ if you are doing Managed C++ / Whidbey / CLI or whatever we're supposed to call it.

Though, &H0 looks like Visual Basic .NET - see http:/Programming/Programming_Languages/Dot_Net/ for all the .NET goodies.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now