Conversion char into int

Posted: May 31, 2013 in Programming
Tags: , , , , , , ,

This is a link to my program on github that converts char into int.

https://github.com/admix/admixSoft/blob/master/OOP344/ascToInt.cpp

Would love to get a feedback or suggestions 🙂

//  This block of code performs conversion char to int
//  Returning '0' if not a number
//  ascToInt.cpp
//  Created by Alexander on 2013-05-21.
//  Copyright (c) 2013 Alexander. All rights reserved.
//
#include <iostream>

using namespace std;
int ascToInt(const char *ch);

int main(){  //sample main() where you can test the function
  int num;
  char* str;
  cout<<"Enter a number: ";
  cin>>str;
  num = ascToInt(str);
  cout<<"number = "<<num<<endl;
  return 0;
}

int ascToInt(const char *ch){
  int out;
  int calc;
  
  out = 0;
  calc = 1;
  while (((*ch) == '+') || ((*ch) == '-')){  //checking the sign
    if (*ch == '-') calc = calc * -1; //if negative
    ch++;
  }
  do{ //converting char by char
    out = (out * 10) + ((*ch) - '0'); //substracting 48 to get the real number
    ch++;
  }while((*ch <= '9') && (*ch >= '0'));  //checking if it’s a number
  
  return (out * calc);
}

</num<

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s