473,239 Members | 1,736 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,239 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 8421
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...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.