Reading numeric input one by one

This is a discussion on Reading numeric input one by one within the C Programming forums, part of the General Programming Boards category; I am trying to create a program where a user can enter a value like 1234 and the output will ...

  1. #1
    Registered User oval's Avatar
    Join Date
    Jan 2006
    Location
    Texas
    Posts
    10

    Reading numeric input one by one

    I am trying to create a program where a user can enter a value like 1234 and the output will print according to my assigned values of 1, 2, 3 and 4.

    i.e. 1=ABC, 2=DEF, 3=GHI, 4=JKL, ..... and so on.

    Example:

    User enters: 123

    Output Displayed: ABCDEFGHI

    I know how I am going to code my conditional statements, but I don't know how to read the user input intenger by integer in order to display the results I want.

    Any suggestions would really be appreciated.

    Thanks.

  2. #2
    old man
    Join Date
    Dec 2005
    Posts
    90
    Use fgets() to get a string of user input from stdin ... then parse it.

    You'd run into a problem if you wanted to use a value greater than 9 -- then you'd need to use a token to separate numeric strings (a comma is a common choice). In your case, however, with each digit representing three letters of the alphabet, you'll be okay ...

    Instead of conditional statements here, I'd go with indexing into an array of strings ...

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,265
    Code:
    char buff[32];
    char *p;
    char output[64];
    /* fill buff with the user input */
    
    p = buff;
    output[0] = 0;
    while(*p)
    {
       switch(*p++)
       {
          case '1':
             strcat(ouput,"ABC");
             break;
          case '2':
             strcat(output,"DEF");
         etc....
       }
    }
    Things to keep in mind though:
    - Don't overflow the output buffer by writing in too many characters.
    - You need to handle bad input. What if a user inputs "12F4A"? Also fgets() will append a \n

  4. #4
    Registered User
    Join Date
    Dec 2005
    Location
    Australia - Melbourne
    Posts
    63
    try functon getchar() as the condition of a while loop, with switch (or if) statements and strcat in the loop itself(i think your confused - look below).

    here is how it will work.
    1. in condition of while loop:
    getchar() gets a character and assigns it to a char variable - if that character is '\n' it exits loop
    2. in loop
    if input is recognized add the appropriate string to the end of a char array (strcat(nameofarray, "text to add").
    if not do something- i don't know (error message maybe).
    3. out of while loop (the user pressed enter)
    print the array.

    note: you will need to assign nameofarray[0] = '\0' before the while statement or there will be trouble.

  5. #5
    Registered User oval's Avatar
    Join Date
    Jan 2006
    Location
    Texas
    Posts
    10
    Thanks Everyone, I really appreciate the help.

  6. #6
    old man
    Join Date
    Dec 2005
    Posts
    90
    Here's what an implementation of my suggestions would look like:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    /* arbitrary values */
    #define IN_SIZE 16
    #define OUT_SIZE (IN_SIZE * 3) + 1
    
    
    void
    clr_stdin (char *s)
    {
      char ch, *p;
      if ((p = strchr (s, '\n')) == NULL)
        while ((ch = getchar()) != '\n' && ch != EOF)
          ;
      else *p = '\0';
    }
    
    
    int
    main (void)
    {
      char inbuf[IN_SIZE], outbuf[OUT_SIZE];  int i;
      char *alpha[] = {
        "ABC","DEF","GHI","JKL","MNO","PQR","STU","VWX","YZ"
      };
    
      while (1)
      {
        printf ("\nEnter your numbers > ");
        if (fgets (inbuf, IN_SIZE, stdin))
        {
          if (!(isdigit (*inbuf)))
            break;
          clr_stdin (inbuf);
    
          *outbuf = '\0';
          for (i = 0; inbuf[i] != '\0'; i++)
          {
            if (isdigit (inbuf[i]) && inbuf[i] != '0')
              strcat (outbuf, alpha[(inbuf[i]-'0')-1]);
          }
          if (*outbuf == '\0')
            strcat (outbuf, "(invalid)");
          printf ("Your output: %s\n", outbuf);
        }
      }
      printf ("\nGood bye\n\n");
      return 0;
    }
    Last edited by eerok; 01-23-2006 at 06:45 PM.

  7. #7
    Registered User
    Join Date
    Dec 2005
    Location
    Australia - Melbourne
    Posts
    63
    well here is my version
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        
        char output[100];    // stores the message to be displayed after input
        char x;              // stores the immediate character entered
        
        printf("Enter numbers to convert into text: ");
        output[0] = '\0';              // this is important 
        
        while ( (x=getchar()) != '\n') {
            // adds an appropriate text to output depending on input 
            switch (x) {
                case '0': 
                    strcat(output, "ABC");
                    break;
                case '1':
                    strcat(output, "DEF");
                    break;
            }
        }
        printf("\nignoring invalid inputs the text is....\n");
        printf("%s", output);
    
        while (getchar() != '\n') ;
        return 0;
    }

  8. #8
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by eerok
    Here's what an implementation of my suggestions would look like:
    Same thing only different:
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    void foo(const char *text)
    {
       static const char *output[] =
       {
          "","ABC","DEF","GHI","JKL","MNO","PQR","STU","VWX","YZ",
       };
       for ( ; *text != '\0'; ++text )
       {
          if ( isdigit(*text) )
          {
             fputs(output[*text - '0'], stdout);
          }
       }
       putchar('\n');
    }
    
    int main(void)
    {
       char text[80];
       fputs("prompt: ", stdout);
       fflush(stdout);
       if ( fgets(text, sizeof text, stdin) != NULL )
       {
          foo(text);
       }
       return 0;
    }
    
    /* my output
    prompt: 123
    ABCDEFGHI
    */
    It just ignores any nondigit text and goes straight to the stdout rather than using a string.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  9. #9
    old man
    Join Date
    Dec 2005
    Posts
    90
    Quote Originally Posted by Dave_Sinkula
    It just ignores any nondigit text and goes straight to the stdout rather than using a string.
    Yes, the string isn't necessary ... it's just a mindset thing I guess (you never know what you can make use of later)

    I'm curious about your use of 'fflush (stdout)', though -- it's something I've never found cause to use: is it very common for a system to withhhold the buffered data on stdout?

  10. #10
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by eerok
    I'm curious about your use of 'fflush (stdout)', though -- it's something I've never found cause to use: is it very common for a system to withhhold the buffered data on stdout?
    In my preferred environment (SlickEdit's build window), yes, and I find that fortunate.

    Without it:
    C:\Test>GnuC\myapp.exe
    123
    prompt: ABCDEFGHI
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  11. #11
    old man
    Join Date
    Dec 2005
    Posts
    90
    C:\Test>GnuC\myapp.exe
    123
    prompt: ABCDEFGHI
    Yes, that's no good at all. Now I understand

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need some help with C program writing
    By The_PC_Gamer in forum C Programming
    Replies: 9
    Last Post: 02-12-2008, 09:12 PM
  2. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 04:42 PM
  3. Help with linked list (and reading user input)
    By p1kn1c in forum C Programming
    Replies: 2
    Last Post: 04-05-2006, 01:43 AM
  4. Trouble with a lab
    By michael- in forum C Programming
    Replies: 18
    Last Post: 12-06-2005, 11:28 PM
  5. Reading input as an integer
    By n0de in forum C++ Programming
    Replies: 4
    Last Post: 04-11-2002, 07:52 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21