Question about limiting inputs in C

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 2K views
doktorwho
Messages
181
Reaction score
6
I want to write a program that in the twodimensional array stores only capital and noncapital letters of the alphabet and the sign #. Everything else inputted cannot be stored in the array. How am i to do this in the easiest way?
I can think of only checking for each input if it exists in some array i created with only those letters and the sign but that seems like a lot of work. Is there an easier way that i don't know of?
 
Physics news on Phys.org
Characters are stored in C as numbers according to their ASCII codes. Just check to see if each input character falls within the range of numbers corresponding to the letters of the alphabet or #.
 
  • Like
Likes   Reactions: doktorwho
You can compare single chars using the same comparison operators as for numbers, e.g.

Code:
char first = 'f';  // or read it in with a scanf() or whatever
if (first > 'a')
{
    // do something
}
else
{
   // do something else
}

For lowercase letters, compare for the range from 'a' to 'z'; for uppercase, 'A' to 'Z', just like you would for a range of numbers.

You might also investigate the character-testing functions in ctype.h, e.g. isalpha(), islower(), isupper().
 
You have two ranges and a discrete value that it can be, so do an if.

C:
int isInputValue(char value){
     if (value >= 'A' && value <= 'Z') return 1;
     if (value >= 'a' && value <= 'z') return 1;
     return (value == '#') ? 1 : 0;
}
 
jtbell said:
You might also investigate the character-testing functions in ctype.h, e.g. isalpha(), islower(), isupper().

This is the portable way to do it. (As well as not reinventing functionality already in the standard library.)
C:
#include <ctype.h>

int is_alpha_or_hash(int c)
{
    return isalpha(c) || c == '#';
}
Doing things like c >= 'A' && c <= 'Z' is making the code dependent on assumptions about the character encoding used by the C compiler (which is implementation-defined, even if many implementations use ASCII or similar in practice).
 
  • Like
Likes   Reactions: jim mcnamara and newjerseyrunner