Thread: Validating Text Input

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    1

    Validating Text Input

    Hi guys, fairly new to C.
    Basically, i'm just creating a simple data entry form and i was wondering if there was another way apart from using strcmp to validate text input.
    for example, i already have this:

    Code:
    	do
    	{
    		printf("Enter your favourite sport from these options (Football, Basketball, Hockey or Baseball): ");
    		scanf("%s", sport);
    		for (i = 0 ; i < (int)strlen(sport); i++)
    		{
    			if (i == 0) cpu[i] = toupper(sport[i]);
    			else sport[i] = tolower(sport[i]);
    		}
    	}
    	while (strncmp(sport, "Football", 8) != 0 && strncmp(sport, "Basketball", 10) != 0 && strncmp(sport, "Hockey", 6) != 0 && strncmp(sport, "Baseball", 8) != 0);
    at the moment, it doesn't accept input other than those sports but is there another way to do this without using strncmp?

    thanks guys!

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    strncmp() limits comparison to n characters. So if someone typed "Footbally" it would still match. May not be what you want. strcmp() would be better because the lengths of words must match also.

    You could put all the allowable words in an array:
    char *allowed[] = { "Football", "Basketball", "Hockey", ... };

    Then loop through using
    Code:
    for (i = 0; i < sizeof(allowed) / sizeof(*allowed); i++) {
        if (!strcmp(sport, allowed[i])) {
            ... do stuff ....
            }
        }
    Also, instead of forcing the input to conform to certain capitalization, use stricmp() which ignores case.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can someone help me with these errors please code included
    By geekrockergal in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 02:20 PM
  2. 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
  3. Parsing Text File and gathering input variables
    By azamsharp1 in forum C Programming
    Replies: 2
    Last Post: 10-26-2005, 08:43 AM
  4. input from text using structures
    By ehj3000 in forum C Programming
    Replies: 12
    Last Post: 09-16-2005, 10:30 PM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM