Thread: explanation

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    33

    explanation

    for this program, I prompt the use to enter a string. after the string is executed, the program will then execute to convert all lowercase letters into upper case.

    Code:
    #include<stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    main()
    {
    	char x[100];
    	int i = 0;
    
    	printf("Enter a string: ");	
    	gets(x);
    
    	for(i = 0; x[i] !=0; i++)
    	{
    		x[i] = toupper(x[i]);
    	}
    
    	printf("%s\n", x);
    }
    But when I use another char array to represent the new uppercased strings it would output an extra character.

    Code:
    #include<stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    main()
    {
    	char x[100];
    	char l[100];
    	int i = 0;
    
    	printf("Enter a string: ");	
    	gets(x);
    
    	for(i = 0; x[i] !=0; i++)
    	{
    		l[i] = toupper(x[i]);
    	}
    
    	printf("%s\n", l);
    }
    Sample run for the first program.

    Code:
    Enter a string: This is A teSt
    THIS IS A TEST
    Sample run for the 2nd program with an l char array:

    Code:
    Enter a string: This is A teSt
    THIS IS A TEST9
    As you can see, there's an excess char '9' in the executed program. Can anyone explain as to why this happens?

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    There is no NULL terminator character in the second array to tell printf "here is where the string stops". You will need to add the terminator, or initialize your arrays with 0s
    Code:
    char l[100] = { 0 };
    Also, you should not be using gets. gets is BAD.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    33
    thank you!

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Code:
    for(i = 0; x[i] !=0; i++)
    {
       l[i] = toupper(x[i]);
    }
    l[i] = 0;
    You need to null terminate the string.
    Last edited by CommonTater; 12-04-2010 at 04:28 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Network Prog. Game over net. Explanation
    By clzola in forum C Programming
    Replies: 4
    Last Post: 11-09-2010, 12:23 PM
  2. Linked Lists
    By Bleu_Cheese in forum C++ Programming
    Replies: 13
    Last Post: 12-21-2007, 09:17 PM
  3. Explanation of switch statements
    By ammochck21 in forum C++ Programming
    Replies: 6
    Last Post: 11-04-2006, 02:59 PM
  4. printf function explanation
    By vice in forum C Programming
    Replies: 3
    Last Post: 09-21-2005, 08:35 PM
  5. basic linked list declaration..need explanation
    By aspand in forum C Programming
    Replies: 3
    Last Post: 06-07-2002, 05:55 PM