Thread: What Would You Use To Read User Input?

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    32

    Question What Would You Use To Read User Input?

    basically i have a struct with some various char arrays and ints. i have already used these throughout the program when reading from a file so i dont really want to change these.

    anyway i ask the user to input their address (it must be a full line of text - eg. 123 Fake St Fakeville 90210). i was wondering what others would use to read it in all at once.

    as i said above i have done a read from file function (user has 2 options - from file, or from input) and used fgetc(...) to read it all in (including ints) and it worked fine.

    scanf(...) - would i have trouble diferentiating between ints, chars, and strings? and would there be trouble if the user put in maybe 2 spaces between words instead of 1? and would there be trouble if a user put in 4 numbers for a street number when the maximum is 3?

    getch(...) - do a char at a time and use while and for loops to go over extra spaces if there are any and continue to read in as chars like in my read from file function? and would getch allow the user to type it out on the screen or would i need putch with it?

    or is there something else i could use?

    heres my struct if that helps.
    Code:
    char flat_unit[MAX][UNIT_MAX = 3];
    int flat_number[MAX][NUMBER_MAX = 3];
    char flat_divider[MAX];
    int number[MAX][NUMBER_MAX = 3];
    char street_name[MAX][STR_MAX = 256];
    char street_type[MAX][STR_MAX = 256];
    char suburb_name[MAX][STR_MAX = 256];
    int postcode[MAX][POSTCODE_MAX = 4];
    so what would people do themselves? maybe an example as well please.

    thanks so much to everyone.
    Last edited by djwicks; 03-31-2005 at 10:50 PM. Reason: Incomplete

  2. #2
    Registered User
    Join Date
    Mar 2005
    Posts
    135

    ...

    I would try to avoid scanf/fscanf because it's more susceptible to errors. I would personally use fgets or fgetc for FILE reading (prefer fgetc for flexebility) and gets() for input from stdin (standard input device - keyboard).

    For reading from a FILE, I would do something like this:

    Code:
    int c, i = 0;
    char buff[200];
    
    while ( (c = fgetc(fp)) != EOF ) // if not end of file, loop.
    {
    
    if ( !(c == ' ') ) // if not space, do.
    buff[i++] = c;
    
    }

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    Avoid using gets() even when reading from standard input:
    http://faq.cprogramming.com/cgi-bin/...&id=1043284351

    Use fgets() instead.

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    135

    oopsie

    Yeah, that too - forgot

  5. #5
    Work in Progress..... Jaken Veina's Avatar
    Join Date
    Mar 2005
    Location
    Missouri. Go Imos Pizza!
    Posts
    256
    I would probably use fgets() or a loop of getch() to read in all of the characters at once and store them in a temporary array. Then, I would read through the array, one character at a time and determine what the character is and where in the struct it belongs. Then simply put it there.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Why use getch when it's not standard? Use getchar instead.

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User
    Join Date
    Mar 2005
    Posts
    32
    ok so i think ill use getch(). now if i were to read in this line of input:

    "123 Fake St Melbourne 3000"

    how would i do it and allow the user to see what they r typing at the same time in getch()? all this assuming that i would just read it into a temp array first and work up where to put it later.

    thanks once again.

  8. #8
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    This is another method in which you may or may not want to use:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    #define MAX 10
    
    struct address {
            int street_number;
            char* street_name;
            char* suburb_name;
            int postcode;
    };
    
    struct address addbook[MAX];
    
    int main(int argc, char** argv)
    {
            char* result = NULL;
            char buf[BUFSIZ];
            char *delims = " \n\t";
            int input = 1;
            int i = 0;
    
            if (fgets(buf,BUFSIZ,stdin) == NULL)
            {
                    fprintf(stderr,"Error getting info\n");
                    exit(1);
            }
    
            /* Else process the data */
    
            result = strtok(buf,delims);
            while (result != NULL && input <= 4)
            {
                    /* read into different parts of the array depending on input */
                    if (input == 1) {
                            addbook[i].street_number = atoi(result);
                    } else if (input == 2) {
                            addbook[i].street_name = malloc(strlen(result) + 1);
                            if (addbook[i].street_name == NULL)
                            {
                                    fprintf(stderr,"Could not allocate mem!");
                                    exit(1);
                            }
                            addbook[i].street_name = result;
                    } else if (input == 3) {
                            addbook[i].suburb_name = malloc(strlen(result) + 1);
                            if (addbook[i].suburb_name == NULL)
                            {
                                    fprintf(stderr,"Could not allocate mem!");
                                    exit(1);
                            }
                            addbook[i].suburb_name = result;
                    } else if (input == 4) {
                            addbook[i].postcode = atoi(result);
                    }
                    input++;
                    result = strtok(NULL,delims);
            }
    
            /* Print out the structure to test if it works */
    
            printf("Street Number: %d\n",addbook[i].street_number);
            printf("Street Name: %s\n",addbook[i].street_name);
            printf("Suburb Name: %s\n",addbook[i].suburb_name);
            printf("Postcode: %d\n",addbook[i].postcode);
    
            return 0;
    }
    Its still a bit messy but it may help you get an idea of what you want to do. Basically I used strtok() to break up the string read in by fgets(). Then individual tokens are placed into different parts of the structure depending on the "input" variable. Also I changed some of your structure details - instead of having a MAX on all the individual structure members I simply just made an array of structures of max size MAX.

    The code above only shows input for the first index of the "addbook" structure. You will need to reset both the "input" and "i" variables if you wish to read into the second index. Also, you need to tweak some of the code (obviously) to how you want it done.

    A sample input/output:
    Code:
    bash-3.00# ./parse1
    123 FakeSt Melbourne 3000
    Street Number: 123
    Street Name: FakeSt
    Suburb Name: Melbourne
    Postcode: 3000
    As you can see I had to combine Fake St into FakeSt, you can correct this yourself if you need to. You may also want to use a switch statement since you will have lots of if statements otherwise - the choice is yours.
    Last edited by 0rion; 04-03-2005 at 06:26 AM.

  9. #9
    Registered User
    Join Date
    Dec 2004
    Posts
    12
    I don't know whether the suggestion that i am giving is right or wrong, so please correct me if it is so.

    I am not considering the file reading example as u already seem to have done that. As far as the keyboard input is concerned, my suggestion is : don't trust the user input; instead, keep the flow in your control, like :

    enter street (press enter for none) : 123
    enter street name (press enter for none) : Fake street
    enter suburb name (press enter for none) : fake

    This way, u can have the validation as well as input region under ur control, and code would be shorter. U can use functions

    All the best

  10. #10
    Registered User
    Join Date
    Mar 2005
    Posts
    32
    thats great but i want to read from the input. so fgetc would clearly not work. right? anyway i must read it in as a whole line from the user input because it says i must.

    how would this code work for the following? any ideas on what to change?

    --> 123 Fake Street Melbourne 3000


    Code:
    char c, char temp[MAX];
    int a, b, c, d, e, counter;
    ...
    
    printf("please enter whole address line:\n");
    while((c = getch()) != '\n') // i want to be able to see it typed in here up to the end of line character
    {
       temp[MAX] = c; // should i use a puts or something to see it typed in?
    }
    // now i should have the whole line in the temp up to the end of line character, right?
    
    for(a = 0; a < MAX_NUMBER_SIZE; a++)
    {
       counter++; //increment along read in array
       while(temp[counter] != '(space)')
       {
          street_number[0][b] = temp[counter]; // i should have the '123' bit in now?
       }
    }
    
    for(b = 0; b < MAX_STRING_SIZE; b++)
    {
       counter++; //increment along read in array
       while(temp[counter] != '(space)')
       {
          street_name[0][b] = temp[counter]; // i should have the 'Fake' bit in now?
       }
    }
    
    for(c = 0; c < MAX_STRING_SIZE; c++)
    {
       counter++; //increment along read in array
       while(temp[counter] != '(space)')
       {
          street_type[0][c] = temp[counter]; // i should have the 'Street' bit in now?
       }
    }
    
    for(d = 0; d < MAX_STRING_SIZE; d++)
    {
       counter++; //increment along read in array
       while(temp[counter] != '(space)')
       {
          suburb_name[0][d] = temp[counter]; // i should have the 'Melbourne' bit in now?
       }
    }
    
    for(e = 0; e < MAX_POSTCODE_SIZE; e++)
    {
       counter++; //increment along read in array
       if(temp[counter] == '(space)')
       {
           e--; // minus 1 from loop counter for space being found in temp
       }
       else
       {
          postcode[0][e] = temp[counter]; // i should have the '3000' bit in now?
       }
    }
    ...
    so would that be alright for just 1 address to start? or maybe i have it worng with the whole 'while not space' loops inside the for loops. would i do the while loop again and again and make the for loop in fact run for longer than i really want? and if so then maybe i could have a if statement and minus 1 from the for loop count (like how i have done the last one). plz help. thanx.

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    If you're not understanding how a function works, you can always write a small test program to get familiar with it. Like so:
    Code:
    #include <stdio.h>
    
    int main( void )
    {
        char array[ BUFSIZ ] = {0};
        int x;
    
        printf("Enter a line of text: ");
        fflush( stdout );
    
        for( x = 0; x < BUFSIZ-1; x++ )
        {
            array[ x ] = fgetc( stdin );
            if( array[ x ] == '\n' )
            {
                array[ x ] = '\0';
                break;
            }
        }
        printf("You entered: \'%s\'\n", array );
    
        return 0;
    }
    Quzah.
    Hope is the first step on the road to disappointment.

  12. #12
    Registered User
    Join Date
    Dec 2004
    Posts
    12
    Brother, don't make it complex.. I am sorry for the statement, but that's exactly what u r doing. I personally like HTML forms and the way they take input, one input per box, that's how it should be...

    keep it simple. Handle one entry per input. Take one part at a time. It will help u in long run. Trust me.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-03-2008, 09:07 PM
  2. User determined input question
    By lyoncourt in forum C Programming
    Replies: 8
    Last Post: 09-30-2007, 06:10 PM
  3. large program code ,please help
    By Ash1981 in forum C Programming
    Replies: 14
    Last Post: 01-30-2006, 06:16 AM
  4. Read a 4x4 matrix from user input
    By JHaney in forum C++ Programming
    Replies: 9
    Last Post: 11-29-2005, 07:56 PM
  5. Ending user input with # character
    By jowatkins in forum C++ Programming
    Replies: 2
    Last Post: 04-27-2004, 10:41 AM