首页 > 解决方案 > 使用 atoi 时返回值为 0

问题描述

我在命令行参数中输入了一个数字,如果有一个“+”或“-”字符,我试图把它去掉,只留下数字。我设法去掉了前导字符,但是每当我尝试用 atoi 分配没有前导字符的字符串的值时,我一直得到的值是 0。想知道我可能做错了什么,因为每当我打印出字符串时,它的完全相同的字符串除了没有前导字符,atoi 函数不应该将其转换为数字吗?ReadLine() 函数接受一个字符串并根据用户输入的大小动态分配内存。

char *val = ReadLine();
  int i, size = strlen(val);
  int count = 0;
  int num = 10;
  char *newVal = (char*)malloc(sizeof(char) * 10);
  for(i = 0; i < size; i++) //checks once to make sure its proper formatting, if count == size then input is correct
  {
    if((val[0] == '+' && i == 0) || (val[0] == '-' && i == 0))
    {
      //printf("check\n");
      count++;
      i++;
    }
    if(val[i] >= '0' && val[i] <= '9')
    {
       count++;
    }
  }
  printf("the count is %d\n\nand the size is %d\n", count, size);
  while(count != size)    ///input check to make sure user is inputting correct values.
  {
    //repeat
    count = 0;
    val = ReadLine();
    size = strlen(val);
    for(i = 0; i < size; i++)
    {
      if((val[0] == '+' && i == 0 ) || (val[0] == '-' && i == 0)){
        //printf("check\n" );
        count++;
        i++;
      }
      if(val[i] >= '0' && val[i] <= '9')
      {
        //printf("%c\n", val[i]);
        count++;
      }
    }
    printf("count: %d\nsize: %d\n", count,size);
  }
  char numb[size-1];
  if(val[0] == '+')
  {
    //char *fin = (char*)malloc(sizeof(char) * size - 1);
    for(i = 1; i < 2; i++)
    {
      strcat(numb,&val[i]);
      count++;
      break;

    }
    printf("value of numb = %s\n", numb);
    newVal = (char*)realloc(newVal,sizeof(size-1));
    newVal = numb;
    printf("Value of newVal = %s\n", newVal);

    num = atoi(newVal);

    printf("The string is %s", newVal);
    return num;
  }
  else if (val[0] == '-')
  {
    for(i = 1; i < 2; i++)
    {
      strcat(numb,&val[i]);
      break;
      count++;
    }
    printf("value of numb = %s\n", numb);
    newVal = (char*)realloc(newVal,sizeof(size-1));
    newVal = numb;
    printf("Value of newVal = %s\n", newVal);
    num = -1 * atoi(newVal);
    printf("the num is%d\nstring is : %s",num, numb);
    return num;
  }
  //now convert that string to integer whether its plus or negative.
  num = atoi(val);
  return num;

这是我使用的输入,这就是它打印回来的内容。

Please enter a value
-1248
the count is 5
and the size is 5
value of numb = 1248
Value of newVal = 1248
the num is 0
string is : 1248
The value you put was: 0

标签: cstringatoi

解决方案


推荐阅读