整数错误 C

Integer error C

这是我现在拥有的:

int main() {
int number;
printf("Type your number: ");
scanf("%i",&number);

char code[4];
printf("Type your code: ");
scanf("%s",&code);

当我在第一个输入除数字以外的任何内容时,脚本都变得疯狂,它只是显示

Type your number: NOTaNUMBER

Type your code: THErestOFtheSCRIPT

-- 回到命令行

我想要它做的是

Type your number: NOTaNUMBER

You didn't enter a number

-- 回到命令行

我该怎么做?


这与上述副本不同。我在这里谈论的是 C,而不是 C++。 C不知道cin,对上述重复的答案。然而,下面找到了答案

对于输入字符串使用

  scanf("%s",code);

或更好

  scanf("%3s",code);

检查 scanf 返回的数字使用值是否正确输入:

   char ch;
   if( 1 == scanf("%i",&number) )
   {
        // use correct number
   }
   else
   {
        // clean input bufer
       while( (ch = getchar()) != '\n' && ch != EOF);
   }