如何在C中解析美元和美分

时间:2014-10-07 02:53:14

标签: c

假设我有一个3.50(字符串)的输入,我如何解析它以便它存储为3美元和50美分。美元和美分都是整数,不允许使用atoi。

我考虑到了这一点,但显然它在C中不起作用(假设令牌是3.50):

dollars = int(token); /* dollars is 3 */
cents = atoi(token) - dollars; /* atoi is not allowed but I can't think of anything else */

谢谢!

4 个答案:

答案 0 :(得分:2)

您是否要将自己的string推送到int解析器......

int parse_int(char **s) {
  char sign = **s;
  if (sign == '-' || sign == '+') {
    (*s)++;
  }
  int result = 0;
  unsigned char ch;
  while (isdigit(ch = **s)) {
    (*s)++;
     // By accumulating the int on the negative side, we can parse INT_MIN
    result = result * 10 + '0' - ch;
  }

  if (sign != '-') result = -result;
  return result;
}


void parse_dollars_cents(char **s, int *dollar, int *cent) {
  *dollar = parse_int(s);
  if (**s == '.') {
    (*s)++;
    *cent = parse_int(s);
  } else {
    *cent = 0;
  }
}


int main(void) {
  char buf[100];
  fgets(buf, sizeof buf, stdin);
  int dollar, cent;
  char *s = buf;
  parse_dollars_cents(&s, &dollar, &cent);
  printf("$%d.%02d\n", dollar, cent);
  return 0;
}

答案 1 :(得分:1)

您可以使用sscanf

sscanf(stringWhereDollarCentValueIsStored , "%d.%d" , &dollars , &cents);

答案 2 :(得分:0)

假设您之后的分数只有2位小数且令牌为double,则从令牌中减去美元并乘以100。

dollars=int(token);
token-=dollars;
cents=int(token*100.);

编辑:从评论开始,tokenchar *

int dollars, cents;
sscanf(token,"%d.%d",&dollars,&cents);

编辑2:从评论开始,没有itoa()sscanf()

按照here所述实现以下功能。然后使用它:

double amount=parseFloat(token);
dollars=int(amount);
cents=int((amount-dollars)*100.);

答案 3 :(得分:0)

您需要修改这些以正常处理无效输入,但这些函数将使用有效输入:

int get_dollars(char *str)
{
    int i = 0;
    int accum = 0;

    // While the current character is neither the null-terminator nor a '.' character
    while(str[i]&&str[i]!='.')
    {
        // Shift any previously accumulated values up one place-value by multiplying it by 10
        accum *= 10;
        // Add the numeric value of the character representation of the digit in str[i] to accum
        // (('0'-'9')-0x30=integer value 0-9)
        accum+=str[i]-0x30;
        // Increment the loop counter
        i++;
    }
    // Return the result
    return accum;
}

int get_cents(char *str)
{
    int i = 0; 
    int accum = 0;
    int start_pos = 0;
    // Get the location of the '.' character so we know where the cent portion begins at
    while(str[i]&&str[i]!='.') {i++; start_pos++; }
    i = start_pos+1;
    // Same algorithm as get_dollars, except starting after the '.' rather than before
    while(str[i])
    {
        accum *= 10;
        accum += str[i]-0x30;
        i++;
    }
    return accum;
}