gpt4 book ai didi

c - 读取多个 ASCII 字符并获取值

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:33 25 4
gpt4 key购买 nike

有人可以解释或纠正我的代码吗?我正在尝试输入几个字符并获取 ascii 值

例如:输入:ab;输出:9798

这是我的代码,但最后有一个 10

#include <stdio.h>

int main() {
char c;
printf("Enter any character\n");

for (c=0; c<=122; c++)
{
scanf("%c", &c);
printf("%d",c);
}
return 0;
}

最佳答案

如果你看ASCII table ,十进制值 10 是换行符。换句话说,您将 \n 字符作为输入的一部分进行处理。例如,当用户复制粘贴多行或按下 Enter 键时,可能会发生这种情况。如果您不希望这种情况发生,您需要格外小心以忽略 \n。例如:

#include <stdio.h>

int main() {
char c;
printf("Enter any character\n");

for (c=0; c<=122; c++)
{
scanf("%c", &c);
if (c == '\n')
break; /* Or perhaps continue? Depends on what you actually want. */
printf("%d",c);
}
return 0;
}

另外,请注意不同的系统对于换行符的实际含义可能有不同的约定。在 UNIX 上,它只是 \n 字符,在 Windows 上,它可能是 \r\n 的组合。所以如果你想让你的程序具有可移植性,就需要考虑到这一点。您可以自己做,也可以使用其他库(想到 GNU getline)。您可以阅读有关换行符的更多信息 here .

关于c - 读取多个 ASCII 字符并获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com