0

我想在 ANSI C 中编写一个提示用户输入的代码。首先,我想打印提示。然后,我想回显提示并循环,仅当输入并回显字符时。

我知道要进行无限循环,我必须将 while() 的条件设置为始终为真的东西,例如 while(1)

但是,当我测试我的代码时,似乎我一遍又一遍地循环打印“输入一个字符”。对 C 的新手有什么建议吗?

#include <stdio.h>

int main()
{

char mychar;

while(1)
    printf("Enter a characater:\n");
    scanf("%c", &mychar);
    printf("%c", &mychar)
}
4

2 回答 2

8

C 中的块不是基于缩进的(例如在 python 中)。块必须以 开头{和结尾},如下所示:

while(1)
{
    printf("Enter a characater:\n");
    scanf("%c", &mychar);
    printf("%c", mychar);// NOTE the missing `&` in front of `mychar` here
}
于 2013-04-17T06:37:39.953 回答
0

You should use an editor or an IDE which can autoformat/autoindent entire source files. If you had such a thing, you would have immediately seen the problem, because your code would look like this:

int main()
{
  char mychar;

  while(1)
    printf("Enter a characater:\n");
  scanf("%c", &mychar);
  printf("%c", &mychar)
}

And this is a mistake even experienced C programmers sometimes make, so having the simple cure (autoindent/autoformat code) for it is important even in future.


Unrelated problem, you pass pointer to char for %c format specifier in your latter printf. You should enable warnings on your compiler, it would warn you about that.

于 2013-04-17T06:47:35.417 回答