-4

This is what I have now:

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

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

When I type anything but numbers in the first one the script goes all crazy, it just shows

Type your number: NOTaNUMBER

Type your code: THErestOFtheSCRIPT

-- Back to command line

What I want it to do is

Type your number: NOTaNUMBER

You didn't enter a number

-- Back to command line

How can I do this?


This is different from the said duplicate. I'm talking about C here, not C++. C doesn't know cin, the answer to the said duplicate. However, an answer was found below

Community
  • 1
  • 1

1 Answers1

1

For input string use

  scanf("%s",code);

or better

  scanf("%3s",code);

To check correct input for number use value returned by scanf:

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