Solved

Converting chars to int

Posted on 1997-11-19
4
277 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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
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 goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
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…

839 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