gets(), reverse(), and strlen() help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • goldenllama
    New Member
    • Oct 2006
    • 3

    gets(), reverse(), and strlen() help

    Hi, thanks in advance for the assistance.

    I need to make a program that will take a string using gets() (I know gets() is bad, but it's what I'm supposed to use), and then print the message in reverse. One problem I had was that when I used gets(message);, the program just continued without letting me enter anything. I'm using while(strlen(ge ts(message)) == 0); right now and it seems to work, but I'd prefer to use gets(message); if I can.

    In any case, here's my code so far:

    Code:
    #include <stdio.h>
    #include <math.h>
    main(void)
    {
            int menu, n, n_end, length;
            char message[111];
    
            printf("\nHomework 4:\n\n");
            printf("There are two parts: part 1 and part 2.\n");
            printf("Enter the part number to execute (1 or 2):");
            scanf("%d", &menu);
            switch(menu){
                case 1:
                    printf("Part I:\n\n");
                    printf("\nEnter a text message:");
                    while(strlen(gets(message)) == 0);
                    printf("\nYour message is:\n%s\nMessage Length: %d",message,strlen(message));
                    /* Code to reverse message here */
    
                   printf("\n\nYour message in reverse is:\n%s",message);
                    printf("\n");
                    break;
    Case 2 will include some math stuff, which is why math.h is there and why the code is incomplete.

    In any case, I'm not entirely sure how to make reverse work or why gets() isn't working for me. Did I screw something up somewhere?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Originally posted by goldenllama
    In any case, I'm not entirely sure how to make reverse work or why gets() isn't working for me. Did I screw something up somewhere?
    No it is picking up the Enter you will have pressed after entering a menu option.

    Try changing you scanf string to "%d\n"

    or flushing stdin after you have done the scanf to clear input data with

    rewind(stdin);

    NOTE don't

    fflush(stdin)

    because the action of fflush is undefined for input streams.

    Comment

    Working...