Thread: Function calling

  1. #1
    Registered User
    Join Date
    Sep 2007

    Function calling

    I have a menu driven program that should point towards several functions depending on the user's input.

    One of the functions is supposed to prompt the user to enter a string and then determine whether or not it is a palindrome.

    When the function is called upon it prints the prompt text then immediately states, without any user input, that the string is a palindrome. Could someone take a look and let me know why it is ignoring the input?

            char string[20];
            int first, last;
            printf("Enter a string (max 20 char): ");
            fgets(string, 20, stdin);
            for (first = 0, last = strlen(string) - 1; first < last; first++, last--)
                    if(string[first] != string[last])
                            printf("This string is not a palindrome. \n");
            printf("This string is a palindrome. \n");

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    Most likely, you end up with an empty string because there is a pending newline in the input buffer from some previous input operation (getchar() or scanf() for example). And by the method you have used, an empty string is a palindrome, because if strlen(string)-1 is zero, then you never enter the loop [because first < last is not true] - and even if you did, it would still compare character 0 with character 0 of the string, which by all logic should be true.

    The solution is to make sure that any newline left behind from some other input operation is properly removed before you attempt to input the string.

    There is one other option - the stdin file is at end of file, which also leads to an empty file. But my guess is that this is not the case.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  3. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Question on function syntax and calling function
    By cbrman in forum C Programming
    Replies: 10
    Last Post: 10-05-2003, 05:32 PM