Thread: using string in arrays

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    18

    using string in arrays

    i am trying to make a program that takes a string as an input from the user and then prints it in reverse order. but i'm having some problems. here is the source code that i wrote:

    Code:
    #include <stdio.h>
    int main ()
    {
    	char a[10];
    	int i;
    
    	for (i=0;i<10;i++)
    	{
    			printf("Enter a String:\n");
    			scanf("%c",&a[i]);
    	}
    		printf("You entered: %c\n",a[i]);
    	
    		for (i=9;i>=0;1--)
    	{
    			printf("The reverse is: %c",a[i]);
    	}
    }

  2. #2
    Registered User
    Join Date
    Nov 2006
    Posts
    176
    the first for loop is going to ask the user to enter a string 10 times
    I think you want somthing more like
    Code:
            printf("Enter a String:\n");
            scanf("%s",a);
    the second printf is printing the 9th char in the string
    try

    Code:
            printf("You entered: %s\n",a);
    the second for loop should be
    Code:
           printf("reverse:");
            for (i=strlen(a);i>=0;i--)
            {
                    printf("%c",a[i]);
            }
            printf("\n");
    the faq has good examples of getting strings from users I believe, try looking there for how to do this correctly
    Last edited by sl4nted; 11-30-2006 at 10:32 AM.

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    i=strlen(a);
    a[i] will be null
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    Registered User
    Join Date
    Nov 2006
    Posts
    176
    not if I edit really quickly

    your right my mistake, shove a -1 in there too

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM
  5. string handling
    By lessrain in forum C Programming
    Replies: 3
    Last Post: 04-24-2002, 07:36 PM