Validating data in C

I tested a simple program in C to validate user data. It is assumed that the program determines whether the character entered by the user is a number, alphabet, or special character.

Somehow, the code identifies each type of input character as a number. I added the code below, I would appreciate if someone could kindly indicate where I am mistaken?

// Program user input and determine if it is a character, number, or special character

#include<stdio.h>
#include<conio.h>
#include<string.h>


    char ch;

int main()

{
     clrscr();

    printf("Enter a character \n");
    scanf("%c \n",ch);

    if ((ch>='A'&& ch<='Z')||(ch>='a'&& ch<='z') )
    {
        printf("The character entered is an alphabet \n" );

    }
     else if ((ch>=0)&&(ch<=9))
    {
        printf("Character entered is an number \n");
    }


    else
    {
        printf("Character entered is a special character");

    }
    return 0;
}
+3
source share
3 answers

scanftakes a pointer as an argument to %c. In other words,

scanf("%c \n",ch);

should be written as:

scanf("%c\n",&ch);

(&) scanf ch. , ch . * ch scanf ch, ch, scanf ch ( *).

, Himadri .

* undefined.

+4

, . , 0 9 .

, -

if ((ch>='A'&& ch<='Z')||(ch>='a'&& ch<='z') )
{
    printf("The character entered is an alphabet \n" );

}
 else if ((ch>='0')&&(ch<='9'))
{
    printf("Character entered is an number \n");
}
else
{
    printf("Character entered is a special character");

}

, . .

+1

:

  • conio.h clrscr() .
  • (char ch). .
  • Always check the return value scanf. This will help you catch input format errors. In this case, since we need only one character, it is getcharmore appropriate.

Here is how I wrote this program:

#include <stdio.h>
#include <ctype.h>

int main()
{
  int ch; /* We use an int because it lets us check for EOF */
  printf("Enter a character: ");
  fflush(stdout); /* Remember to flush the output stream */
  ch = getchar();
  if (ch == EOF)
    {
      printf("end-of-file or input-error\n");
      return 1;
    }
  if (isalpha(ch))
    printf("The character entered is an alphabet\n" );    
  else if (isdigit(ch))
    printf("Character entered is an number\n");    
  else
    printf("Character entered is a special character\n");    
  return 0;
}
0
source

Source: https://habr.com/ru/post/1759260/


All Articles