Thread: printf waits until main returns to display

  1. #1
    Registered User
    Join Date
    Jan 2010
    Posts
    16

    printf waits until main returns to display

    I am using the most up-to-date eclipse IDE for C/C++. I have the below code. It seems simple enough. My problem is that no printf will display on the console until the main has finished (return 0). This means I get a prompt in console asking for input before I get the message telling me what to do. I fill in a number like 10 and I see 10 is now displayed in stdout followed by the first and second printf. Can anyone explain why this is? What am I doing wrong?
    Code:
    #include <stdio.h>
    
    int main(void) {
    	int n = 0;
    	int i = 0;
    	int left = 1;
    	int right = 1;
    	int temp = 1;
    
    	printf("Enter an index: ");
    	scanf("%d", &n);
    	printf("Index: %d", n);
    	if (n < 0 || n == 0) {
    		printf("\nFibonacci index: %d\n", -1);
    	}
    	if (n == 1) {
    		printf("\nFibonacci index: %d\n", 1);
    	}
    	for (i = 0; i < (n - 1); i++) {
    		temp = right;
    		right = left + temp;
    		left = temp;
    	}
    	printf("\nFibonacci index: %d\n", left);
    
    	return 0;
    }
    Last edited by brightmatter; 01-28-2010 at 11:51 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > printf("Enter New Index: ");
    Try
    Code:
    printf("Enter New Index: ");
    fflush( stdout );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Here's what happens when I run this:

    Enter New Index: 4
    Index: 4
    Fibonacci index: 3


    which is exactly what I would expect. You say "I get a prompt in console asking for input before I get the message telling me what to do." I don't see any such message in the code you posted.

    What happens for you? How is this different than what you expect?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Jan 2010
    Posts
    412
    @MK27
    I read his post as if he is not seeing any output from the first printf before the scanf is waiting for input.
    Flushing of the output buffer is from what I understand implementation-specific, and some systems require either a \n or a manual flushing of the buffer to print to the console.

    @brightmatter:
    Does a
    Code:
    printf("Enter New Index:\n");
    work?

  5. #5
    Registered User
    Join Date
    Jan 2010
    Posts
    16
    yes, printf works but it will not appear until after the main has returned... no printf or putchar will show anything in console until end of program. I also tried this:

    Code:
    	char ca[] = {'E', 'n', 't', 'e', 'r', ' ', 'a', 'n', ' ', 'i', 'n', 'd', 'e', 'x', ':', ' ', '\n'};
    
    	for(i = 0; i < sizeof(ca); i++) {
    		putchar(ca[i]);
    	}
    with the same result.

    I tried fflush( stdout ); and it works great now, thank you.

  6. #6
    Registered User
    Join Date
    Jan 2010
    Posts
    412
    Quote Originally Posted by brightmatter View Post
    I tried fflush( stdout ); and it works great now, thank you.
    Cool. Then as a fun mental excercise you could write a variadic function that calls printf() and fflush() automatically for you

  7. #7
    Registered User
    Join Date
    Jan 2010
    Posts
    16
    One disadvantage of learning a higher language first (like Java) is that you tend to assume every language will guide you, inform you, protect you and generally coddle you. I get in to C and it does no such thing. It is a dumb, unbending, brute of a language; capable of powerful acts if it is whipped enough. It has no class (that is a joke).

  8. #8
    Registered User
    Join Date
    Jan 2010
    Posts
    412
    Edit:
    Nevermind this.. I totally misunderstood bright's post.. *blushes*

  9. #9
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by brightmatter View Post
    One disadvantage of learning a higher language first (like Java) is that you tend to assume every language will guide you, inform you, protect you and generally coddle you. I get in to C and it does no such thing. It is a dumb, unbending, brute of a language; capable of powerful acts if it is whipped enough. It has no class (that is a joke).
    Meh. I had a very dissimiliar experience coming from perl, which is higher level than java. While it's sort of irritating writing 10 lines instead of 1, and generally having to do everything yerself, I found C's "unforgiving" and "low level" nature interesting, and it's functionality provides a strong contrast, making me a more well rounded programmer (I hope). I also think the low level thing can provide you with certain opportunities to really "hone in" on the nature of a task (by nature, I mean the hardware's nature) that you otherwise wouldn't get.

    Donuts and holes dude Another cliche: It's a poor workman who...
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  10. #10
    Registered User
    Join Date
    Jan 2010
    Posts
    16
    Ok, I tried this (likely ignorant) approach. The problem is that I am seeing now is that when it passes the char[] "Enter an index: " it only really gives the function 32-bits worth (i.e. four characters) of the array and stops there. This means I can now print four characters of every string I give it. Should I just pass the pointer and then iterate through the array?

    Code:
    #include <stdio.h>
    void printf_n_flush(char print_this[]);
    
    int main(void) {
    printf_n_flush("Enter an index: ");
    return 0;
    }
    
    void printf_n_flush(char print_this[]) {
    	int i;
    	for(i = 0; i < sizeof(print_this); i++) {
    		putchar(print_this[i]);
    	}
    	fflush( stdout );
    }
    Last edited by brightmatter; 01-28-2010 at 12:41 PM.

  11. #11
    Registered User
    Join Date
    Jan 2010
    Posts
    412
    Quote Originally Posted by brightmatter View Post
    Ok, I tried this (likely ignorant) approach. The problem is that I am seeing now is that when it passes the char[] "Enter an index: " it only really gives the function 32-bits worth (i.e. four characters) of the array and stops there. This means I can now print four characters of every string I give it. Should I just pass the pointer and then iterate through the array?

    Code:
    #include <stdio.h>
    void printf_n_flush(char print_this[]);
    
    int main(void) {
    printf_n_flush("Enter an index: ");
    return 0;
    }
    
    void printf_n_flush(char print_this[]) {
    	int i = sizeof(print_this);
    	while (i != 0) {
    		putchar(print_this[i]);
    		i--;
    	}
    	fflush(stdout);
    }
    That's because sizeof is giving you the size of the pointer to the array, not the array itself.
    You could do
    Code:
    int i=0;
    char ch;
    while(ch = print_this[i++])
    {
        putchar(ch);
    }
    edit:
    But I believe the best solution is indeed a variadic function or you're going to run in to trouble when you want to print the
    printf("\nFibonacci index: %d\n", left);
    Check out http://www.gnu.org/s/libc/manual/htm...Functions.html and vprintf()
    Last edited by _Mike; 01-28-2010 at 12:44 PM.

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    If all you want to do is print a string, anything beyond
    Code:
    printf(blah,blah,blah); fflush(stdout);
    is completely out to lunch, cookoo, lost in lala land, people will think you are totally crazy, etc.

    It is also very weird that you would have to use flush like this. Generally, standard output on a normal operating system (nb -- this has nothing to do with C!) happens reasonably soon.

    Anyway, you can set autoflushing on stdout thus:
    Code:
    setvbuf(stdout,NULL,_IONBF,0);
    You could also use puts(), which writes unbuffered to stderr.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #13
    Registered User
    Join Date
    Jan 2010
    Posts
    16
    I did the below... seems to work but you are right that it will not do printf stuff. I will read the link to see if I can come up with something.

    Code:
    void print_string(char print_this[]) {
    	char *print_this_ptr = print_this;
    	while(*print_this_ptr != 0) {
    		putchar(*print_this_ptr);
    		print_this_ptr++;
    	}
    	fflush( stdout );
    }

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Just to remind you again: You are on the wrong path. There can be absolutely NO REASON to write your own print_string function (other than boredom, or as an exercise).

    Go look at some C source. NOBODY does this. NOBODY. You can be the first exception, but that should give you reason to stop and pause. You are confused about something, or something else is very wrong.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  15. #15
    Registered User
    Join Date
    Jan 2010
    Posts
    16
    setvbuf(stdout,NULL,_IONBF,0); works GREAT! Much easier and applies to every printf I do. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems reading entered race times C
    By loopymoo26 in forum C Programming
    Replies: 12
    Last Post: 05-23-2009, 07:38 AM
  2. Polynomials and ADT's
    By Emeighty in forum C++ Programming
    Replies: 20
    Last Post: 08-19-2008, 08:32 AM
  3. I need help on this particular Linked List problem
    By sangken in forum C Programming
    Replies: 11
    Last Post: 08-06-2006, 12:26 AM
  4. whats wrong with this?
    By petedee in forum C Programming
    Replies: 32
    Last Post: 01-06-2004, 10:28 PM
  5. Tab Controls - API
    By -KEN- in forum Windows Programming
    Replies: 7
    Last Post: 06-02-2002, 09:44 AM