Getchar

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gilly
    New Member
    • Mar 2007
    • 6

    Getchar

    Sorry these may sound like stupid questions but how does getchar work? I know that it reads the data one by one in ASCII code but how can u tell it to store numbers only and print an error message if other characters are used? For an assignment i receive 5 dice values, which are entered, i'm have to display a error message if the numbers are entered with a space between them e.g 1 2 3 4 5 is ok but 1.2.3.4.5 is not. Sorry if this sounds stupid, but i have only just started and help as u can tell.

    Thanks for any reply
  • Savage
    Recognized Expert Top Contributor
    • Feb 2007
    • 1759

    #2
    No,it's not a stupid question.

    Here is how getchar works:

    getchar() reads from stdin and is line buffered which means that it won't
    return anything until you press ENTER.After pressing ENTER it will convert input
    to int.

    To solve ur problem you will need to search for signs like '.' and others.If any of
    them exist you will print out a error.


    Savage

    Comment

    • Savage
      Recognized Expert Top Contributor
      • Feb 2007
      • 1759

      #3
      Sorry for double post but here is one way:

      First you must create array that will contain signs that are not allowed:

      Code:
      char a[15];/*This takes care for signs from 33-47 in ASCII signs.*/
      int i,c,good=1;
      /*c will represent a variable used by getchar().*/
      use for loop to create a array:

      Code:
      for(i=0;i<15;i++) a[i]=33+i;/*This will include signs beetwen 33-47,inclusive.*/
      then after using getchar() you must again run same for loop with only one differance it must compare c with possible signs in array.If there is any of them
      change good to zero.After that test like:

      Code:
      if(good==0) /*Print error.*/
      Note: this will only take care for signs beetwen 33-47,inclusive.I suggest that you use same proces to create more arrays of signs because there is more of
      them!!!!.


      Savage

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Have a look at the macros
        Code:
        isdigit(x)
        isspace(x)
        both defined in <ctype.h>

        kind regards,

        Jos

        ps. the getchar() function/macro doesn't do line buffering, nor any buffering
        itself at all; it's the stream that does the buffering. stdin is line buffered by
        default indeed.

        Comment

        • gilly
          New Member
          • Mar 2007
          • 6

          #5
          Thank You so much

          Comment

          Working...