C语言将char类型 '0' -'9'转换成int类型打印到stdout

标签 c char int stdout

我编写了一个程序来接收用户输入并将其打印到屏幕上。

样本输入是abc 12 34

示例输出为abc 12 34,但1234 应作为整数输入。

使用示例输入,我的程序始终输出为 abc 122 344 。我已经研究了很长时间,但我仍然无法弄清楚。可以帮我检查一下我的代码吗?谢谢。

我的 gcc 版本是 4.1.2 。

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char c;
    char *str = NULL;
    str = (char *)malloc(20*sizeof(char)); /*just sample code, not robust*/
    memset(str,'\0',20*sizeof(char)); 

    if(str == NULL)
    {
        fprintf(stderr,"Error: failed to allocate memory.\n"); fflush(stderr);
        return 0;
    }

    /*store user input*/
    int index = 0;
    while((c=getchar()) != '\n')
    {
        *(str+index) = c;
        index++;
    }

    int digit = 0;
    for(index = 0; *(str+index)>0; index++)
    {
        if((*(str+index)>='a') &&( *(str+index)<='z'))
        {
            fprintf(stdout,"%c",*(str+index)); fflush(stdout);
        }

        else if((*(str+index)>='0') &&( *(str+index)<='9'))
        {
            /*handling the case that a number with more than one digit*/
                    if(*(str+index+1)>='0' && *(str+index+1)<='9')
            {
                digit=10*(digit+atoi(str+index));
            }
            else
            {
                digit += atoi(str+index);   
                fprintf(stdout,"%d",digit); fflush(stdout);
                digit = 0;
            }           
        }

        else
        {   
            fprintf(stdout,"%c",*(str+index)); fflush(stdout);
        }
    }
    printf("\n");
    free(str);
    return 0;
}

最佳答案

你不应该使用 atoi : 它将字符串转换为 int , 不是一个char .

情况如下:当您看到一个两位数时,例如 34 ,第一次迭代将两个数字都设为 atoi , 得到 34 , 并将其乘以十,使得 340 .以下迭代选择 4 , 并愉快地将其添加到 340 , 对于 344 的累积结果.

如果您想转换单个 char表示 int 的数字,使用减法:

digit = *str - '0';

此外,您处理多位数字的代码非常不正统,因此很难理解。当您看到下一个字符是数字时,不要将当前值乘以十,而当您看到数字时,您应该将先前值乘以十。当先验值为 0 时,这甚至适用于第一位数字,因为十次零仍然是零。

你应该删除 if(((*str+index+1)>='0') && (*str+index+1)<='9')及其 then分支,修改其else分支如下:

digit = 10*digit + *(str+index) - '0';
if (((*str+index+1)<'0') || (*str+index+1)>'9') {
    fprintf(stdout,"%d",digit); fflush(stdout);
    digit = 0;
}

关于C语言将char类型 '0' -'9'转换成int类型打印到stdout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089953/

相关文章:

c - 使用指针的差异与 printf ("%.*s")

c++ - 检测浮点软件仿真

Android - 如何获取 TextView 中字符的坐标

C. 使用 scanf() 与允许的字符列表后,无法获取输入字符的值

c - 为什么命令行参数 -12345678969 被认为是 >1?

python - 为什么 Python 中的整数需要三倍的内存?

在 Linux 中创建简单的 Shell

c - 文件的openssl aes256加密

c - 如何添加仅允许 a-f || 之间的字母的 "(if)"A-F?

java - 找不到符号,我做错了什么?