1

我对 K&R C 第 2 版中的 atoi() 函数示例有一些问题。只能使用 0 到 9 的字符。但是在我的程序逻辑的某个地方我做错了。

所以里面有这个功能:

#include <stdio.h>

int atoi(char s[]);

int main()
{
    int i;
    char ch;
    char co[50]; 
    int  ci[50];

    while(ch != EOF )
    {

        for(i=0;i<50-1 && (ch=getchar()) != EOF && ch != '\n';++i)
        {
            co[i] = ch;
            /*ci[i] = atoi(co[i]);*/ /*bugged*/
            ci[i] = atoi(co);
            printf("%d \n",ci[i]);
        }
        if(ch == '\n')
        {
            co[i] = '\n';
        }
        ++i;
        co[i] = '\0';
    }

    return(0);

}

/* as in the book: */
/* atoi: convert s to integer */

int atoi(char s[])
{
    int i, n;
    n = 0;
    for(i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
    {
        n = 10 * n + (s[i] - '0');
    }

    return(n);
}

以下是我得到的错误:

|In function 'main':
19|warning: passing argument 1 of 'atoi' makes pointer from integer without a cast [enabled by default]
3|note: expected 'char *' but argument is of type 'char'
||=== Build finished: 0 errors, 1 warnings (0 minutes, 0 seconds) ===|
4

3 回答 3

2

(s[i] = '0')

应该读

(s[i] - '0')

(注意减号而不是等号)。

这会将字符'0'..转换'9'为数值0.. 9

你也没有atoi()正确调用。它需要一个字符串,而不是一个char. 您可能应该从循环外部调用它。

而且ch不是正确的类型(应该是int)。

于 2013-04-10T18:22:01.073 回答
1

atoi();函数需要指向字符串的指针。char*这就是警告的原因warning: passing argument 1 of 'atoi' makes pointer from integer without typecase

你声明 co 喜欢:char co[50]; 但称atoi(co[i]);这是错误的,

注意它说的是 int 而不是 char。

一个例子:

atoi("1");有效但atoi('1'); 无效。

所以即使co是正确的但"12345678"不正确的。atoi(co)atoi(co[i])

于 2013-04-10T18:26:20.167 回答
1
printf("%c = ",co[i]);
ci[i] = atoi(co[i]);
printf("%d \n",ci[i]);

您正在尝试将 char 转换为 int,但 char整数值。所有你需要的是

printf("%c = %d\n", co[i], co[i]);

如果你想要的是char的十进制值。如果您要做的是将 ASCII 数字转换为整数,那么

printf("%c = %d\n", co[i], co[i] - '0');

会做。

于 2013-04-10T18:33:53.530 回答