2013년 5월 21일 화요일

AscToInt(const char *num);


int AscToInt(const char *num){
  int no;
  no = 0;
  while(*num != 0){
    if(*num >= '0' && *num <= '9'){
      no = no*10+ (*num-48);  // 48 == '0'
      num++;     // to the next address of the character(the number)
    }
    else{
      cout<<"num is not NUMBER"<<endl;
      return 0;
    }
  }
  return no;
}

--------------------------------------------------------------------------------------

after i read other's code, i realized that this code doesn't work for negative.
so,


int AscToInt(const char *num){
  int no;
  int i;
  no = 0;
  for(i=0;num[i]!=0;i++){
    if(num[i] == '-'){
      continue;
    }
    else if(num[i] >= '0' && num[i] <= '9'){
      no = no*10+ (num[i]-48);
    }
    else{
      cout<<"num is not NUMBER"<<endl;
      return 0;
    }
  }
  if(num[0] == '-')
    return (-1)*no;
  else
    return no;
}