gpt4 book ai didi

c - 如何避免在 while 循环中打印 '\n' 的 ASCII 值?

转载 作者:太空狗 更新时间:2023-10-29 15:29:53 26 4
gpt4 key购买 nike

我的任务是获得一个输入,打印出字符和 ASCII 值,并以 1 行每 8 位显示它们。对于我输入的每个输入,我也得到了换行符的值,我不想打印它。

这是我的代码:

#include <stdio.h>

int main()
{
char ch;
int count = 0;

printf("please type an input:\n");
while ((ch = getchar()) != '#')
{
++count;
printf("%c=%d ", ch, ch);
if (count%8 == 0) printf("\n");
}
}

最佳答案

您可以在阅读第一个后立即使用另一个 getchar():

  while ((ch = getchar()) != '#')
{
getchar(); // To eat the newline character
// Rest of code
}

或者您可以使用 scanf() 并等效地重写循环:

   while (scanf(" %c", &ch)==1)
{
if(ch != '#')
{
++count;
printf("%c=%d ", ch, ch);
if (count%8 == 0)
printf("\n");
}
}

关于c - 如何避免在 while 循环中打印 '\n' 的 ASCII 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14553882/

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