473,406 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Confused at newline requirement for printf

Hi,
I read in many places that the string to be outputted by printf()
must be ending with newline, for example, it should be

printf("Hello World.\n");

instead of

printf("Hello World.");

because the latter is "undefined" by standard.

But I tried the following code:

#include <stdio.h>

int main(){
printf("%d", 15);

printf("Type in some number:");
int i;
scanf("%d", &i);
printf("\nHey you typed in %d", i);

return 0;
}

You can see that I do not have '\n" in any of the printf, I see what
I expected:

$>./a.out
15Type in some number:9

Hey you typed in 9$>

I know this could be because the compiler implements the support
and also when program finishes the buffer gets flushed out.

My real question is like this, we see a lot of use cases that
printf() and scanf() are used together, as in my example, use printf()
to prompt user to type in something and then use scanf() to read it
in. It is best not to move the curer to a new line.

Then how that requirement that printf() should end with newline
comes to play?

Sep 21 '07 #1
1 8466
linq936 wrote:
Hi,
I read in many places that the string to be outputted by printf()
must be ending with newline, for example, it should be

printf("Hello World.\n");

instead of

printf("Hello World.");

because the latter is "undefined" by standard.
Not exactly. A "line" of text usually ends with a
newline character, and if you don't supply one the
implementation might not treat whatever characters you
have already supplied as a "line." But there is no
requirement that all the characters of a "line" must
be output at the same time:

printf ("Hell");
x = sqrt(y);
printf ("o brave new World ");
x += atan(x, y);
printf ("that hath such creatures ");
x *= y;
printf ("in it!");
x = 42;
printf ("\n");

.... uses five printf() calls to generate one "line" of
output, and is perfectly all right. Each of the first
four printf() calls generates part of a "line," and the
fifth makes it complete. As long as the newline comes
along "eventually," all is well.
But I tried the following code:

#include <stdio.h>

int main(){
printf("%d", 15);

printf("Type in some number:");
int i;
scanf("%d", &i);
printf("\nHey you typed in %d", i);

return 0;
}

You can see that I do not have '\n" in any of the printf, I see what
I expected:

$>./a.out
15Type in some number:9

Hey you typed in 9$>

I know this could be because the compiler implements the support
and also when program finishes the buffer gets flushed out.
The implementation is trying to be helpful, probably by
flushing all pending output on all streams whenever you use
an input function on any stream. Not all implementations will
be so helpful (indeed, some may be intentionally *un*helpful,
because excessive output flushing defeats the purpose of
buffering and may hurt performance).

Also, it appears that this implementation can tolerate
"lines" that lack a newline terminator. Not all can do so.
Some implementations use entirely different methods to divide
a file into "lines," such as preceding each line with a number
giving its length. Such implementations cannot even begin to
output a line until the '\n' has appeared and the length can
be computed; if the '\n' never shows up it's anybody's guess
what will happen to the still-buffered data.

The blank line is probably (*probably*) caused by the
implementation echoing the newline (or newline-equivalent)
that ended your input, not by anything your program did on
its own.
My real question is like this, we see a lot of use cases that
printf() and scanf() are used together, as in my example, use printf()
to prompt user to type in something and then use scanf() to read it
in. It is best not to move the curer to a new line.

Then how that requirement that printf() should end with newline
comes to play?
Best practice: Make the prompt be a complete line, with
newline and all. If there's any chance that the output stream
might be "fully buffered," call fflush() before attempting input.
This will put the prompt and the response on separate lines,
but if the system is incapable of handling a partial line that's
the best you can manage anyhow.

Second-best practice: Prompt with a newline-less line, and
call fflush() before reading the response. This stands a fairly
good chance of forcing the prompt to appear, and a fairly good
chance of allowing the response to occupy the same line on the
terminal.

Third-best practice: Call setvbuf() very early to make the
prompting stream unbuffered. Then proceed as in the second-
best scenario, but now you can omit the fflush(). Note that this
will make *all* I/O on the stream unbuffered; if you're going to
begin with a few prompts and then write reams of output you may
not like the performance.

Fourth-best practice: Proceed as you did in the code you
showed, and hope for the best.

Worst practice: Use gets() to read the input.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Sep 21 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Paul Watson | last post by:
I thought that using a comma at the end of a print statement would suppress printing of a newline. Am I misunderstanding this feature? How can I use print and not have a newline appended at the...
4
by: Charles Erwin | last post by:
Is there any way, upon scanning in a file line by line to avoid missing the last line if there is not a newline character (aka you have to hit return on the last line of input in your file). I was...
4
by: Till Crueger | last post by:
Hi, I have a little problem with the following code: #include <stdio.h> int main(void) { char input='\0'; while(input!='q') { printf("Menu\n"); fflush(stdout);
4
by: bacadman | last post by:
I have a variable that seems to be placing a newline when outputting to a file. How can I test to see if this is the case.
8
by: siliconwafer | last post by:
Hi All, If I open a binary file in text mode and use text functions to read it then will I be reading numbers as characters or actual values? What if I open a text file and read it using binary...
33
by: Lalatendu Das | last post by:
Dear friends, I am getting a problem in the code while interacting with a nested Do-while loop It is skipping a scanf () function which it should not. I have written the whole code below. Please...
11
by: timmu | last post by:
Someone asked me a question about integer division and printf yesterday, I tell him he should do a casting to float/double before you do any interger division. But he doesn't think so, so I try...
11
by: Michael | last post by:
I'm new to PHP. I see that PHP supports the C printf function, and I've seen examples like printf("Hello world!\n"); however the newline character \n doesn't work - i.e., it does not generate an...
16
by: bgold12 | last post by:
Will newlines ever be standardized? I recently discovered that in a textarea, internet explorer adds \r\n for every newline you enter, while firefox adds \n. I know \r is also used in some...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.