当我通过 ASCII 十进制代码打印输入的字符时,会打印出奇怪的 10 值
Strange 10 value gets printed when I print inputed characters by their ASCII decimal code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int end;
while(( end = getchar() ) != EOF ){
printf("%d\n",end);
}
system("pause");
return 0;
}
我想用这个代码打印字符的 ASCII 代码,但是每当我 运行 从我这里获取字符后的代码,它会打印它的等价于十进制 10 的 ASCII。例如,如果我 运行 代码并传递“a”,它将打印 97 和 10。为什么它打印 10,所有其他字符也会发生这种情况。
感谢您的回答,作为后续问题,当我输入一个字符计数器的值增加 2 后添加一个计数器时,为什么会发生这种情况
#include <stdio.h>
#include <stdlib.h>
int main()
{
int end;
int count=0;
while(( end = getchar() ) != EOF ){
printf("%d\n",end);
count++;
printf("counter is now %d\n",count);
}
system("pause");
return 0;
}
在 ASCII 中,换行符由值 10 表示。
只要您键入一系列字符并按 ENTER 键,您就会得到所键入的 letters/numbers/symbols 的 ASCII 值以及换行符的值 10。
如前所述,您正在分别打印 'a'
和 '\n'
的 ASCII 十进制代码,这是因为,在您的代码中,getchar
读取 [=15] 中的所有字符=] 缓冲区,包括因为您按 Enter.
而出现的换行符
您可以通过简单地使其被您的条件忽略来避免这种情况:
while((end = getchar()) != EOF && end != '\n'){
printf("%d\n", end);
}
免责声明:David Ranieri 添加了一条评论,其中的解决方案与我正在写我的答案(他善意地删除了)完全相同,所以也归功于他。
关于您的评论问题和问题编辑:
如果您不想 '\n'
打断您的解析周期,您可以简单地将条件放在其中。
while((end = getchar()) != EOF){
if(end != '\n'){ //now as '\n' is ignored, the counter increases by one
printf("%d\n", end);
count++;
printf("counter is now %d\n",count);
}
}
计数器增加 2 的原因再次是因为解析了两个字符,无论您输入什么字符和换行符。正如您在示例中看到的,如果您忽略 '\n'
,则 counter
只会增加一个,前提是您一次只输入一个字符。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int end;
while(( end = getchar() ) != EOF ){
printf("%d\n",end);
}
system("pause");
return 0;
}
我想用这个代码打印字符的 ASCII 代码,但是每当我 运行 从我这里获取字符后的代码,它会打印它的等价于十进制 10 的 ASCII。例如,如果我 运行 代码并传递“a”,它将打印 97 和 10。为什么它打印 10,所有其他字符也会发生这种情况。 感谢您的回答,作为后续问题,当我输入一个字符计数器的值增加 2 后添加一个计数器时,为什么会发生这种情况
#include <stdio.h>
#include <stdlib.h>
int main()
{
int end;
int count=0;
while(( end = getchar() ) != EOF ){
printf("%d\n",end);
count++;
printf("counter is now %d\n",count);
}
system("pause");
return 0;
}
在 ASCII 中,换行符由值 10 表示。
只要您键入一系列字符并按 ENTER 键,您就会得到所键入的 letters/numbers/symbols 的 ASCII 值以及换行符的值 10。
如前所述,您正在分别打印 'a'
和 '\n'
的 ASCII 十进制代码,这是因为,在您的代码中,getchar
读取 [=15] 中的所有字符=] 缓冲区,包括因为您按 Enter.
您可以通过简单地使其被您的条件忽略来避免这种情况:
while((end = getchar()) != EOF && end != '\n'){
printf("%d\n", end);
}
免责声明:David Ranieri 添加了一条评论,其中的解决方案与我正在写我的答案(他善意地删除了)完全相同,所以也归功于他。
关于您的评论问题和问题编辑:
如果您不想 '\n'
打断您的解析周期,您可以简单地将条件放在其中。
while((end = getchar()) != EOF){
if(end != '\n'){ //now as '\n' is ignored, the counter increases by one
printf("%d\n", end);
count++;
printf("counter is now %d\n",count);
}
}
计数器增加 2 的原因再次是因为解析了两个字符,无论您输入什么字符和换行符。正如您在示例中看到的,如果您忽略 '\n'
,则 counter
只会增加一个,前提是您一次只输入一个字符。