-4

I am trying to create a program that reads a user input strings and prints only those are not ‘a-z’ or ‘A-Z’. The following program can print string of characters. But how do I write a C program that reads a user input strings and prints only those are not ‘a-z’ or ‘A-Z’? I appreciate any help that I can get.

#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name);     // read string
printf("Name: ");
puts(name);    // display string
return 0;
}

1 Answers1

1

To start with... Never use gets (nor scanf("%s" …). Use fgets.

Then you just to iterate over the string and check if the individual character is in the range of characters you don't want to print.

#define MAX_LEN 30

int main()
{    
    char name[30];
    printf("Enter name: ");
    if (fgets(name, MAX_LEN, stdin) != NULL)
    {
         int i = 0;
         while (name[i])
         {
            if ((name[i] < 'a' || name[i] > 'z') &&
                (name[i] < 'A' || name[i] > 'Z'))
                putchar(name[i]);
            ++i;
         }
    }

    return 0;    
}

Input:

12john34BEN56 78Al9

Output:

Enter name: 12john34BEN56 78Al9

123456 789
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63