Solved

Converting chars to int

Posted on 1997-11-19
4
266 Views
Last Modified: 2010-04-10
Do you know the algorithm for converting a string of digits, character by character, to a decimal integer?  For example,
if the user entered a string of the characters '1' '2' '3',
how would you convert those digits to another variable of type int with the value 123?
If you know, please email me at:  jose_gutierrez@usa.net
Thanks.
0
Comment
Question by:Jose_G
  • 2
  • 2
4 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 1173601
int atoi (const char *str);

0
 
LVL 22

Accepted Solution

by:
nietod earned 50 total points
ID: 1173602
int
CnvStr2Int(char *Str)
{
   int i = 0;
   while (*Str)
   {
      i *= 10;
      i += *Str++;
   }
   return i;
}
0
 
LVL 84

Expert Comment

by:ozo
ID: 1173603
or
      i += *Str++ - '0';

0
 
LVL 22

Expert Comment

by:nietod
ID: 1173604
whoops.  Yes, you do want to subtract off 0.

int
CnvStr2Int(char *Str)
{
   int i = 0;
   while (*Str)
   {
      i *= 10;
      i += *Str++ - '0';
   }
   return i;
}
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

831 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