Thread: using a string comparison in C

  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    2

    using a string comparison in C

    In this small program what does the 3rd line mean? Specifically on the 3rd line the [16].
    Code:
    int main ()
    	{
    	char s [16];
    
    	printf ("\nMeeting with an ugly boss...");
    	printf ("\nHow are you? (good or bad): ");
    	scanf ("%s", &s);
    	if (strcmp (s,"good") == 0) 
    		printf ("\nBOSS: Nope... You fired!");
    		
    	else 
    		if (strcmp (s,"bad") == 0) 
    			printf ("\nBOSS: Too bad... You fired!");
    			
    		else 
    			printf ("\nBOSS: Not too cooperative today?!... You fired!");
    					
    	printf ("\nBOSS: Ahhh! That feels good!");
    	
    	return 0;
    	}

  2. #2
    Registered User
    Join Date
    Jan 2003
    Posts
    115
    3rd line?
    char s[16] ?

    your declaring an array which can hold 16 characters
    and the first character starting at position 0.
    there are only 10 people in the world, those who know binary and those who dont

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    11
    The [] mean that that s is a array of consecutive characters. The number iside the brackets specifies the number of characters.

    s[0] is the first element of the array, s[1] is the second element array....s[15] is the last element of the array.

    Arrays are commonly used in order to save a string. In your exemple, the array s will hold the string typed by the user (the scanf statement).

  4. #4
    Registered User
    Join Date
    May 2003
    Posts
    2
    Ok, thanks.

  5. #5
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    And this means you're doing it wrong:
    >>scanf ("%s", &s);

    It should be
    >>scanf ("%s", s);
    as s is an array.

    When you're comfortable with using scanf(), have a read of this to see how you might read input in a better manner.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM