Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C/++/# Question about limiting inputs in C

  1. Apr 24, 2017 #1
    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 dont know of?
     
  2. jcsd
  3. Apr 24, 2017 #2

    Drakkith

    User Avatar

    Staff: Mentor

    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 #.
     
  4. Apr 24, 2017 #3

    jtbell

    User Avatar

    Staff: Mentor

    You can compare single chars using the same comparison operators as for numbers, e.g.

    Code (Text):

    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().
     
  5. Apr 24, 2017 #4
    You have two ranges and a discrete value that it can be, so do an if.

    Code (C):
    int isInputValue(char value){
         if (value >= 'A' && value <= 'Z') return 1;
         if (value >= 'a' && value <= 'z') return 1;
         return (value == '#') ? 1 : 0;
    }
     
  6. Apr 24, 2017 #5

    wle

    User Avatar

    This is the portable way to do it. (As well as not reinventing functionality already in the standard library.)
    Code (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).
     
  7. May 1, 2017 #6

    Svein

    User Avatar
    Science Advisor

Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Question about limiting inputs in C
  1. Question about C (Replies: 3)

  2. Questions about C (Replies: 7)

Loading...