To force output to the screen, please see the first section below. The second and third options below are also good for debugging program crashes like these.

Using printf with fflush (refinement of Vishal Kumar's answer)

Vishal Kumar's answer worked for me, but I had to do a little research to find out how to use fflush. I had a problem where my program was crashing "in the middle" of a printf statement which did not make sense. Here is my refinement of his answer. In cases where a debugger is difficult to use (e.g. multithreading), you can use fflush after every printf (or fprintf) statement. For example, "pepper your code" with:

... // code
printf("Part 1 executed successfully");
fflush(stdout); // flushes the stdout buffer
... // further code
printf("Part 2 executed successfully");
fflush(stdout);
... // repeat as necessary

Run, observe the output, and put more print statements between the last statement that prints, and the first statement that doesn't print, until you isolate the problem.

Debugger

If you are able to use a debugger, it is a more efficient choice than peppering your code with output statements as described above, but there are cases where you have to resort to that.

Valgrind

If you are using Linux (which I gather you are not because it is in MS Visual C++), valgrind is another option to see where your code is crashing (and for detecting memory leaks). If your code is compiled for debug, if your program is called "myProgram", you can just call from the terminal window as follows:

valgrind myProgram
Answer from Jonathan on Stack Overflow
Top answer
1 of 1
3

To force output to the screen, please see the first section below. The second and third options below are also good for debugging program crashes like these.

Using printf with fflush (refinement of Vishal Kumar's answer)

Vishal Kumar's answer worked for me, but I had to do a little research to find out how to use fflush. I had a problem where my program was crashing "in the middle" of a printf statement which did not make sense. Here is my refinement of his answer. In cases where a debugger is difficult to use (e.g. multithreading), you can use fflush after every printf (or fprintf) statement. For example, "pepper your code" with:

... // code
printf("Part 1 executed successfully");
fflush(stdout); // flushes the stdout buffer
... // further code
printf("Part 2 executed successfully");
fflush(stdout);
... // repeat as necessary

Run, observe the output, and put more print statements between the last statement that prints, and the first statement that doesn't print, until you isolate the problem.

Debugger

If you are able to use a debugger, it is a more efficient choice than peppering your code with output statements as described above, but there are cases where you have to resort to that.

Valgrind

If you are using Linux (which I gather you are not because it is in MS Visual C++), valgrind is another option to see where your code is crashing (and for detecting memory leaks). If your code is compiled for debug, if your program is called "myProgram", you can just call from the terminal window as follows:

valgrind myProgram
Top answer
1 of 3
55

On many systems printf is buffered, i.e. when you call printf the output is placed in a buffer instead of being printed immediately. The buffer will be flushed (aka the output printed) when you print a newline \n.

On all systems, your program will print despite the missing \n as the buffer is flushed when your program ends.

Typically you would still add the \n like:

printf ("%s\n", a);

An alternative way to get the output immediately is to call fflush to flush the buffer. From the man page:

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function.

Source: http://man7.org/linux/man-pages/man3/fflush.3.html

EDIT

As pointed out by @Barmar and quoted by @Alter Mann it is required that the buffer is flushed when the program ends.

Quote from @Alter Mann:

If the main function returns to its original caller, or if the exit function is called, all open files are closed (hence all output streams are flushed) before program termination.

See calling main() in main() in c

2 of 3
4

Strangely enough, it seems that nobody posted the adjusted code where the buffer is flushed yet...:

#include <stdio.h>

int main (void)
{
    char a[]="abcde";
    printf ("%s", a);
    fflush(stdout);
    //On some systems the line above will fail, in that case use: fflush(NULL);
}

Also note that this code probably doesn't do what you actually want to do.
What I assume you really want to do is:

#include <stdio.h>

int main (void)
{
    char a[]="abcde";
    printf ("%s\n", a);
   //The '\n' makes sure the next thing you print will be on the following line
}
🌐
Reddit
reddit.com › r/c_programming › printf not showing
r/C_Programming on Reddit: printf not showing
October 25, 2022 -

Hi guys,

I have an issue while trying to use the printf. For any reason is not showing no matter in my code.

Could you have a fast look and give me advice of why it's not working? Program simply exits with 0 exit code.

https://i.imgur.com/tQi2QLO.png

I've tried even using printf after the int main(){ but neither is printing anything after running the code through command line!!

🌐
Reddit
reddit.com › r/c_programming › why printf not displaying anything as the program is executed for output
r/C_Programming on Reddit: Why printf not displaying anything as the program is executed for output
September 8, 2023 -
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>

int main(int argc, char *argv[])
{
    if (argc != 2)
        {

            printf("enter only one name of image file");
            return 1;
        }
        string t = argv[1];
        FILE *file = fopen(t, "r");

        if (file == NULL)
     {
        return 1;
     }

int TargetValue = 0x42;
int s = 0;
int c = 0;


while (fread(&s, 1, 1, file) == 1)
{
    if (s == TargetValue)
    {
    c = c + 1;
    printf ("appearance is %i times", c);
    }
    printf ("appearance is %i times", c);
}
printf ("appearance is %i times", c);
fclose (file);
}

Unable to understand why printf not displaying anything despite placed on 3 places. I intentionally pasted printf on three places above.

Here is the output:

recover/ $ ./recover aa
recover/ $ 

🌐
Unix.com
unix.com › applications › programming
why printf don't work? - Programming - Unix Linux Community
September 18, 2009 - I use Solaris 10, I use following code: #include int main(void){ printf("----------testing-----------"); if(signal(SIGUSR1,sig_usr)==SIG_ERR) err_sys("can't catch SIGUSR1"); for(;;) pause(); sig_user(int signo){ ..... } when I run above code,it print nothing in screen.Why?
Find elsewhere
🌐
Reddit
reddit.com › r/cprogramming › printf won't print anything
r/cprogramming on Reddit: Printf won't print anything
October 14, 2023 -

I was trying to complete my homework, and after I run gcc -Wall -Werror -Wextra <filename>.c, none of the print statements show up. I'm running it on Ubuntu. And then I made this test code to see if a simple print statement will show up in a different code and also nothing prints out. There are no error codes, it just doesn't do anything once I press enter. Please help. The link is the test code, I'm not allowed to show my homework:

https://i.imgur.com/FfyRS7m.jp

🌐
Stack Overflow
stackoverflow.com › questions › 73751689 › why-does-the-printf-not-showing
c - why does the printf not showing - Stack Overflow
typedef int* Statistician; void add(Statistician answer, int *count, int *SIZE, int item); | [Note] expected 'Statistician' {aka 'int *'} but argument is of type 'int **' int main() { int SIZE; Statistician *answer; int count; int item; add(answer, count, SIZE, item); | //[Warning] passing argument 1 of 'add' from incompatible pointer type [-Wincompatible-pointer-types] printf("\nThe mean is: %.2f", mean(answer, SIZE)); return 0; }
🌐
STMicroelectronics Community
community.st.com › t5 › stm32cubeide-mcus › printf-not-working-write-never-gets-called › td-p › 276659
Solved: printf() not working - _write() never gets called - STMicroelectronics Community
August 19, 2019 - I checked your code just now and found your printf message does not contain newline "\n" so your printf doesn't hit lower implementation of __io_putchar since stdout is buffered.
🌐
Quora
quora.com › Why-does-printf-not-display-anything-when-used-in-a-library-function-without-main
Why does printf() not display anything when used in a library function without main()? - Quora
The printf statements do not need to be in the main function in C. They have to be in a function that can be reached from the main function. This is because when you run the program, the system starts executing the code in the main function and stops when that function exits.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 149251-print-statement-wont-print.html
Print statement won't print
My code looks right but my print statement won't show up and neither will the decimal points. Please help. I'm using Dev-C++ as my complier. ... #include <stdio.h> #include <stdlib.h> /* Print Farenheit-Celsius Table for fahr = 0, 20, ... ,300 */ main () { float fahr, celsius; int lower, upper, step; lower = 0; /* Lower limit of temperature table */ upper = 300; /* Upper limit of temperature table */ step = 20; /* Step size */ printf("Fahr Celsius \n"); // This line wont print fahr = lower; while (fahr <= upper) { celsius = (5.0/9.0) * (fahr - 32.0); printf("%3.0f %6.1f\n", fahr, celsius); // Decimals aren't showing up fahr = fahr + step; } // end while system ("pause"); }// end main
🌐
GitHub
github.com › rizinorg › cutter › issues › 2651
Printf output not being immediately displayed in the console (output is not line-buffered) · Issue #2651 · rizinorg/cutter
March 30, 2021 - This is probably caused by the printf output not being line-buffered. It can be fixed by adding the following code before the printf statement:
Author   heinosasshallik
🌐
Reddit
reddit.com › r/c_programming › program is ignoring my printf statement
r/C_Programming on Reddit: Program is ignoring my printf statement
March 26, 2021 -

I have a printf statement inside a while loop that gets executed on the first pass, but gets ignored on every subsequent pass. The scanf after it works fine. Why is this happening, and how can I fix it?

Here's my entire main().

void main()
{
	// declare variables
	int intUserSelection = 0;
	int intNumToConvert = 0;
	char strRomanNumerals[50] = "";
	int intIndex = 1;

	printf("Please select one of the three options. Enter 1, 2, or 3 to choose:\n");
	printf("Option #1: Display the first fifty Roman numerals.\n");
	printf("Option #2: Enter a number to be converted to Roman numerals.\n");
	printf("Option #3: Exit.\n");

	scanf("%d", &intUserSelection);

	
	if (intUserSelection == 1)
	{
		DisplayFirstFiftyNumerals();
	}
	else if (intUserSelection == 2)
	{
		while (intIndex == 1)
		{
                        // THIS IS THE STATEMENT THAT GETS IGNORED
			printf("Please enter a whole number between 1 and 3999.\n");
			scanf("%d", &intNumToConvert);

			if (intNumToConvert > 3999 || intNumToConvert < 1)
			{
				printf("ERROR: Number must be between 1 and 3999. Please try again.");
			}
			else
			{
				ConvertIntToNumerals(strRomanNumerals, intNumToConvert);
				printf("%s \n", strRomanNumerals);
				break;
			}
		}

	}
	else if (intUserSelection == 3)
	{
		exit(0);
	}
	else
	{
		printf("ERROR: Input must be 1, 2, or 3.\n");
	}

	system("pause");
}

Thanks for any help, I really appreciate it :)

Top answer
1 of 2
9
printf 'ABC\ctest'

You've hit upon one of the unspecified parts of the printf command, whose behaviour varies from implementation to implementation. You're putting the \c in the wrong place.

If you read the Single Unix Specification's description of printf carefully, you will see that \c is not listed in the list of escape sequences that are defined for the format string (the first argument to the command). Rather, it is defined as an extra escape sequence that is recognized when given in an argument string that is to be formatted by the %b format specifier.

In other words:

  • printf '%b\n' 'ABC\ctest' has a well specified behaviour. The \c causes everything remaining (including the newline in the format string) to be ignored.
  • printf '%s\n' 'ABC\ctest' has a well specified behaviour. The \c is not an escape sequence in the first place.
  • printf '\c' does not have a well specified behaviour. The SUS is simply silent upon what \c is, not listing it as an escape sequence but also not saying in its File Format Notation section that such a sequence is never an escape sequence.

How different shells behave in response to this non-conformant format string varies quite significantly. Here are the Debian Almquist, Bourne Again, FreeBSD Almquist, Korn '93, and Z shells' reactions (with %s showing where no newlines have been emitted):

% dash -c "printf 'ABC\ctest\n'"
ABC\ctest
% bash -c "printf 'ABC\ctest\n'"
ABC\ctest
% sh -c "printf 'ABC\ctest\n'"
ABC%
% ksh93 -c "printf 'ABC\ctest\n'"
ABCest
% zsh -c "printf 'ABC\ctest\n'"
ABC%
%

The builds of the MirBSD Korn and PD Korn shells that I have do not have a printf built-in command. The FreeBSD non-built-in printf does this:

% /usr/bin/printf 'ABC\ctest\n'
ABC%
%

Adding to the fun is that the doco for the various shells is sometimes highly misleading and even sometimes downright erroneous. For examples:

  • The Z shell doco only recently started to give a correct description of what \c does, and lists it (via its doco for echo) as an escape sequence allowed in format strings. (It was incorrect until 2017, the doco neither agreeing with the SUS nor describing what the Z shell actually did.)
  • The Korn '93 shell doco gives a description that is in line with the SUS, but it is not (as can be seen in the aforegiven) what it actually does when \c is in the format specifier. It, too, documents \c as an escape sequence for the format string. Its behaviour is clearly a bug.
  • The doco for the Bourne Again shell and the doco for the Debian Almquist shell give a description of \c that matches the SUS and explicitly list it in relation to %b (in the case of the Bourne Again shell more clearly than it does now up until 2016) and not in a general list of escape sequences for printf format specifiers. These shells do not provide this as an extension to the standard.
  • The FreeBSD Almquist shell doco defers to the FreeBSD external printf command manual, whose description of \c is in line with the SUS. It explicitly lists it as an escape sequence allowed in format strings, and its actual behaviour is as documented in the user manual.

The FreeBSD Almquist shell and (recent) Z shell are the only shells, here, that both document allowing \c as an escape sequence in format strings (an extension to what is defined by the standard) and actually behave as they are documented.

Ironic further reading

  • Why is printf better than echo?
2 of 2
5

It is necessary to expand backslash escape sequences in the corresponding argument. As stated in here:

\c  Terminate output similarly to the \c escape used by echo -e. printf produces no additional output after coming across a \c escape in a %b argument.
$ printf "%b\n" "ABC\chi"
ABC