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 OverflowOn 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
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
}
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!!
Like @thejh said your stream seems to be buffered. Data is not yet written to the controlled sequence.
Instead of fiddling with the buffer setting you could call fflush after each write to profit from the buffer and still enforce the desired behavior/display explicitly.
printf( "Enter first integer\n" );
fflush( stdout );
scanf( "%d", &i1 );
you can try for disabling the buffering in stdout by using
setbuf(stdout, NULL);
#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/ $
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
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 :)
First, main returning void is illegal, please activate warning. Secondly, one of your printf lacks a \n which may explain why it isn't flushed into your terminal by default.
First off, main MUST be declared as returning int!
It works for me. If you enter a number not between 1 and 3999, it prints the "ERROR" print and then loops trough printing the "Please enter..." again.
If you enter a value in range, the thing calls the Convert function, prints the results, and then breaks out of the loop. The thing then falls to the pause (unnecessary if you're running a modern version of Visual Studio that will capture the terminal window automatically).
Output is buffered.
stdout is line-buffered by default, which means that '\n' is supposed to flush the buffer. Why is it not happening in your case? I don't know. I need more info about your application/environment.
However, you can control buffering with setvbuf():
setvbuf(stdout, NULL, _IOLBF, 0);
This will force stdout to be line-buffered.
setvbuf(stdout, NULL, _IONBF, 0);
This will force stdout to be unbuffered, so you won't need to use fflush(). Note that it will severely affect application performance if you have lots of prints.
Apparently this is a known bug of Eclipse. This bug is resolved with the resolution of WONT-FIX. I have no idea why though. here is the link: Eclipse C Console Bug.
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\ccauses everything remaining (including the newline in the format string) to be ignored.printf '%s\n' 'ABC\ctest'has a well specified behaviour. The\cis not an escape sequence in the first place.printf '\c'does not have a well specified behaviour. The SUS is simply silent upon what\cis, 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
\cdoes, and lists it (via its doco forecho) 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
\cis in the format specifier. It, too, documents\cas 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
\cthat 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 forprintfformat specifiers. These shells do not provide this as an extension to the standard. - The FreeBSD Almquist shell doco defers to the FreeBSD external
printfcommand manual, whose description of\cis 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?
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

