Displaying an input backwards

This is a discussion on Displaying an input backwards within the C Programming forums, part of the General Programming Boards category; I am reading the book C Primer Plus , the 5th edition, in order and I'm at the end of ...

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    21

    Displaying an input backwards

    I am reading the book C Primer Plus, the 5th edition, in order and I'm at the end of chapter 6 where they have some review questions. I'm having trouble with this question:

    Write a program that reads in a line of input and then prints the line in reverse order. You can store the input in an array of char; assume that the line is no longer than 255 characters. (Recall that you can use scanf() with the %c specifier to read a character at a time from input and that the newline character (\n) is generated when you press the Enter key.)
    For the "line of input," I'm assuming it takes both letters and numbers.

    Here is what I have so far:

    Code:
    #include <stdio.h>
    #include <string.h>
    int main(void)
    {
    char line;
    int letters;
    char display[letters];
    
    printf("enter a line:\n");
    scanf("%s", line);
    
    letters = strlen(line);
    
    while (letters > 0)
    {
    printf("%s", display[letters]);
    --letters;
    }
    
    return 0;
    }
    When compiling, I got the warning: "first.c:10: warning: passing arg 1 of `strlen' makes pointer from integer without a cast" and when I try to run the program, I get the error: "Segmentation fault (core dumped)."

    Obviously I did it wrong (I'm not following the directions in the parentheses of the question), but anyway, after I got this far, I am stuck on what I should do and I have no clue as to how to go about doing this. Any pointers in the right direction would be appreciated; thanks.

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    line is defined as a character - a one byte character.
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    2

    I help point

    char line;
    int letters;
    char display[letters]; // PROBLEM 1,

    printf("enter a line:\n");
    scanf("%s", line);

    letters = strlen(line); //PROBLEM 2, strlen takes a pointer, not one char. strlen of one char is one.


    Its not over yet, but that will get you a little closer. Post back what you see next.

  4. #4
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    435
    Code:
    char display[letters];
    Is this a standard declaration yet? You want something like char display[255];
    This will make an array with 255 char elements.

    Code:
    while (letters > 0)
    {
    printf("&#37;s", display[letters]);
    --letters;
    }
    This is the right basic idea, but you have a lot of problems with syntax. display[letters] is a single char. %s is used to print a null terminated string. Also, notice that this loop will not print display[0], something you probably want to do.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  5. #5
    Registered User
    Join Date
    Mar 2008
    Posts
    21
    As you can probably tell, I'm pretty new at this (about 24 hours into learning C) so I'm trying very hard to understand from what I already know of the language.

    I was trying to make scanf take the line from the input as a string so each character in the string is placed in a block of an array size of however many characters were entered in the input + 1 (for the null block), then make strlen count the number of blocks (characters) (not including the null block), then assign it to the variable "letters." That was the first step and I knew it was wrong but I didn't know what to do but I tried to move on to the next step anyway, which was take the highest numbered block (the last character of the letters array), print that first, then go down 1 block, print that, etc with the 'display[letters]' thing.

    I'm still trying to make out what's wrong based on the advice provided so far k

  6. #6
    Registered User
    Join Date
    Mar 2008
    Posts
    2
    Code:
    char line;
    int letters;
    char display[letters];  
    
    //you can't declare an array like this. you either hard code it ( display[255] ), or you research pointers and learn how to use malloc.
    
    printf("enter a line:\n");
    scanf("%s", line);  // scanf %s will read until you hit enter, but line is a variable that will only store one char, so you need to change this to be scanf("%s", display) because display will hold more than one character.
    
    letters = strlen(line);  // the length of one character is one, you need to say strlen(display) if you want the string
    
    while (letters > 0)   // you want to print all characters, so while letters >= 0
    {
    printf("%s", display[letters]);
    --letters;
    }
    
    return 0;
    }
    that'll give you a little more direction. however, you might want to pick your variable names better
    Example:
    you declared the variable line as one character and display as multiple characters. I would have done something like:

    char OneChar
    char EntireLine[255];
    int NumberOfChar;

    NumberOfChar = strlen(EntireLine)

  7. #7
    Registered User
    Join Date
    Mar 2008
    Posts
    21
    "//you can't declare an array like this. you either hard code it ( display[255] ), or you research pointers and learn how to use malloc."
    1st comment: Ah, no wonder. malloc is in the very last chapter of this book, and I haven't learned much about pointers yet except the incredibly basic basics.

    "// scanf &#37;s will read until you hit enter, but line is a variable that will only store one char, so you need to change this to be scanf("%s", display) because display will hold more than one character."
    2nd comment: This is much simpler to understand if I set display[255] instead of trying to create an array for the exact number of characters that's input

    "// the length of one character is one, you need to say strlen(display) if you want the string"
    3rd comment: Same as respond for 2nd comment

    "// you want to print all characters, so while letters >= 0"
    4th comment: I saw that and realized my mistake and fixed it, thanks
    Last edited by guitarscn; 03-11-2008 at 10:17 PM.

  8. #8
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    If you only have 24 hours or so of C experience, you probably want to start even more basic. String handling is not something you should delve into it without some good foundations in other aspects of the language.

  9. #9
    Registered User
    Join Date
    Mar 2008
    Posts
    21
    I'm reading the book in order, and I've already done most of the questions with the exception of a few like these. I'm pretty sure after reading chapter 6, that the reader should be able to do the review questions of the chapter, which include everything before it, but nothing that wasn't introduced already. I think the questions are asking, based upon the knowledge the reader knows so far because the book is intended for people without any knowledge of C beforehand or even any programming experience at all (which not might be recommended by other people not to begin with C as their first language). But whatever the chapters have gone over, I think the questions are supposed to be meant for that

    Anyway, so far this is what I understand:

    Code:
    #include <stdio.h>
    #include <string.h>
    int main(void)
    {
    char line; // declares line as a 1 byte character
    int letters;
    
    char display[255]; // sets an array of 255 blocks
    
    printf("enter a line:\n");
    scanf("&#37;s", display); // sets the character(s) input 'display' as a string
    
    letters = strlen(display); // counts the number of characters in the string 'display' and makes the variable 'letters' that amount as an integer
    
    while (letters >= 0) // while the integer 'letters' has more than 0 characters left, (block 0 is the first character)
    {
    printf("%c \n", display[letters]); // output starting from the largest block (the last letter) (I had to change %s to %c because I want to display the character, not a whole string)
    --letters; // move down 1 block then repeat until after block # 0 then the loop ends
    }
    return 0;
    }
    Initially I was just making it real complicated because I was trying to make the array the exact size of the word input first instead of just putting 255 like I was supposed to
    At first it didn't work because I had %s instead of %c in the printf function to display. Now I understand and it looks like it works perfectly!

    Thanks to all (I know this is all simple stuff for everyone else )
    Last edited by guitarscn; 03-11-2008 at 10:45 PM.

  10. #10
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    You should be printing from index (letters-1), not letters. You're currently trying to print the '\0' char first. Also, you're not using the variable line.
    Last edited by MacGyver; 03-11-2008 at 10:49 PM.

  11. #11
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    you may want to add some indentation
    remove unused variable line
    replace comments to the C-style /* */ (// coments are not standard)
    and add explicit cast of the return value of strlen - because it returns size_t value - not int

    Code:
    #include <stdio.h>
    #include <string.h>
    int main(void)
    {
    	int letters;
    	
    	char display[255]; /* sets an array of 255 blocks */
    	
    	printf("enter a line:\n");
    	scanf("&#37;s", display); /* sets the character(s) input 'display' as a string */
    	
    	letters = (int)strlen(display); /* counts the number of characters in the string 
                                	* 'display' and makes the variable 'letters' 
                                	* that amount as an integer 
                                	* we need cast to int to be able to run loop till
                                	* letters >= 0
                                	*/
    	
    	while (letters >= 0) /* while the integer 'letters' has more than 0 characters left, (block 0 is the first character)*/
    	{
    		printf("%c \n", display[letters]); /* output starting from the largest character (the last letter) (I had to change %s to %c because I want to display the character, not a whole string)*/
    		--letters; /* move down 1 character then repeat until index 0 (including) then the loop ends */
    	}
    	return 0;
    }
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  12. #12
    Registered User
    Join Date
    Mar 2008
    Posts
    21
    So is this okay for the code?


    Code:
    #include <stdio.h>
    #include <string.h>
    int main(void)
    {
               int letters;
               char display[255];
    
               printf("enter a line:\n");
               scanf("&#37;s", display);
    
               letters = (int)strlen(display);
               letters -= 1;
    
               while (letters >= 0)
               {
                         printf("%c", display[letters]);
                         --letters;
               }
    
               printf("\n");
    
               return 0;
    }
    Last edited by guitarscn; 03-11-2008 at 11:15 PM.

  13. #13
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    Quote Originally Posted by guitarscn View Post
    So is this okay for the code?
    Yes.

    Just make a mental notice for the future (I do not see a need to deep in this detail right now) that using

    scanf("%s"

    is insecure. It means user can enter more then 255 characters on the same line broking your over data...
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  14. #14
    Registered User
    Join Date
    Mar 2008
    Posts
    21
    Yea, someone earlier was talking about pointers and malloc or something so that probably wouldn't limit it to 255 chars like this one. But thanks, at least the problem is now solved. This isn't that much of a realistic program anyway since it's just practice for the reader of the book to challenge themselves

  15. #15
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    435
    Much better now. Just a couple of suggestions:

    I think a for loop would be preferred over a while in this case.
    Now that everything works, why don't you try the problems suggestion of reading the string in 1 char at a time? Although you probably won't ever actually read from stdin in this fashion, a similar technique will probably be used when you get to file i/o.
    Learn about better ways to read strings. I like using ^ with scanf (read the link in Elysia's signature), but most users here probably prefer some sort of getline function.

    Maybe set those aside for now. Based on your initial attempt, I think you should spend some time on the material you've already learned before trying to go through the book too fast. I wouldn't recommend doing more than 1-2 chapters per day, especially as you get to mre advanced topics.

    And in my opinion, C is probably the best first language. Sure, maybe the syntax is more difficult than say python and the standard library isn't as big as java's, but C is the most versatile and powerful language there is, and most importantly it will teach you good programming practices. C doesn't hold your hand so it's your own responsibility to make sure you don't do something stupid.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  3. Structure and Linked List User Input Question
    By kevndale79 in forum C Programming
    Replies: 16
    Last Post: 10-05-2006, 11:09 AM
  4. Taking input and Outputting it backwards
    By whtpirate in forum C Programming
    Replies: 9
    Last Post: 06-08-2003, 10:59 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21