8

我正在尝试将字符串中的每个字母转换为它的 ASCII 数字。使用

 int letter = (atoi(ptext[i]));

给我这个错误:

error: incompatible integer to pointer conversion
  passing 'char' to parameter of type 'const char *'; take the
  address with & [-Werror]
    int letter = (atoi(ptext[i]));
                       ^~~~~~~~
                       &
/usr/include/stdlib.h:148:32: note: passing argument to parameter
      '__nptr' here
extern int atoi (__const char *__nptr)

以下是我可能相关的其余代码:

    #include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])
{

    printf("Give a string to cipher:\n");
    string ptext = GetString();

    int i = 0;

    if (isupper(ptext[i]))
    {
        int letter = (atoi(ptext[i]));
    }
}

我做错了什么,我该如何解决这个问题,以便将字符串转换为 ASCII 值?

注意:cs50.h让我在 main 中使用“ string”而不是“ char*”。

4

3 回答 3

9

atoi()需要一个字符串。您只需要字符的 char 代码......这是字符本身,因为在 C 中,char就像其他所有整数一样是普通的整数类型,而字符串是chars 的数组,其中包含字符代码本身。

最后,

int letter = ptext[i];

会做的工作。

于 2013-11-09T07:37:32.977 回答
3

您不需要将字符转换为数字。这是对您的数据的解释问题。

字符“A”可以被认为是 0x41 或 65,所以这非常好:

int number = 'A';

变量编号的值是 0x41/65 或 1000001b,具体取决于您希望如何呈现/对待它。

至于解释:如果将 0xFF 呈现为无符号值,则可以将其视为 255,或者将其视为有符号并保留为 8 位时甚至视为 -1。

所以你的问题:

可以将字符串转换为 ASCII 值吗?

有点错误 - 字符串的所有字符都已经是 ascii 值 - 这只是你如何对待/打印/解释/呈现它们的问题。

于 2013-11-09T07:40:47.893 回答
2
int letter = (atoi(ptext[i]));

atoi()将字符串转换为整数而不是字符。

将字符的 ascii 值存储到整数变量中 将字符直接分配给整数变量。

int letter = ptext[i];
于 2013-11-09T07:36:49.673 回答