printf statement is not executing before scanf statement in netbean - c

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,N;
for(i=0;i<5;i++)
{
printf("Enter The Number \n");
scanf("%d", &N);
printf("HELLO %d \n",N);
}
return 0;
}
When i execute the above code in the NetBeans then the output is not being executed line by line all the output is executed together i.e once when the loop end...The problem is printf and scanf are not working

Your description of the problem is actually quite good:
Many C Runtime libraries can detect whether stdout is connected to an interactive device (console window / terminal) or not.
Depending on that, the default buffering mode is selected.
Execute the program on a terminal / in a console window, and you get the standard buffering for interactive devices instead.
Alternatively, calling
setvbuf(stdout, 0, _IOLBUF, BUFSIZ);
before any other operations on that stream will set the stdout stream to default line-buffered operation.

Related

Strange behavior in terminal raw mode

I'm following a tutorial for making a text editor .
So far it's been tinkering with raw mode . The following code is supposed to turn off canonical mode , and output each keypress.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
struct termios orig_termios;
void disableRawMode() { … }
void enableRawMode() { … }
int main() {
enableRawMode();
char c;
while (read(STDIN_FILENO, &c, 1) == 1 && c != 'q') {
if (iscntrl(c)) {
printf("%d\n", c);
} else {
printf("%d ('%c')\n", c, c);
}
}
return 0;
}
I originally forgot to add "\n" after the printf() statements, and the result was that I only got the outputted characters after the program terminates , ie after pressing q in this example .
However after adding "\n", the terminal outputs each letter as pressed.
Could anyone be so kind and explain why is it behaving this way?
Raw-mode is the concern of the terminal but buffer management of stdout occurs before reaching the terminal.
By default, when file-descriptor 1 (STDOUT_FILENO) is link to a terminal, then stdout uses a line-buffering policy.
This means that the output buffer of stdout is flushed to the file-descriptor 1 when a \n is written (or when it is full).
Only at this moment the characters can reach the terminal which can react in different ways depending on its configuration.
In your example, the characters just stay in memory until the process terminates (stdout is flushed at this moment).
Commonly, when a C program starts with the standard output stream connected to a terminal, the stream is line buffered. This means characters printed with printf or standard library methods are kept in a buffer until \n is printed (ending the line, hence “line buffered”), the buffer is full, when the stream is manually flushed (as with fflush), or when input is solicited on stream that is unbuffered or that is line buffered but requires characters from “the host environment” (notably a human).
The terminal setting is irrelevant as the characters are kept in an internal buffer of the standard C library implementation and are not sent to the terminal until one of the above events.
You can set the stream to unbuffered by calling setvbuf(stdout, NULL, _IONBF, 0) before performing any other operation on stdout.

Program does not terminate or comes back with an error for scanf function

This program does not terminate nor does it let me input any values, simply a black screen with no output.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int size;
printf("Enter number of elements in array:");
scanf("%d", &size);
printf("\n%d\n", size);
return 0;
}
Sounds like you're suffering from buffering. Add
fflush(stdout);
after the printf line.
By default, if stdout goes to a terminal, it is line buffered, meaning output is only actually written when the buffer is full or when you output a newline (\n). Terminating the program (via exit() or returning from main) closes all open file handles and also forces a flush.
To make sure output is generated right then and there, call fflush.

Printf not working with scanf

Hi i am new to the programing and for example in my code:
#include <stdio.h>
int main (void){
int a;
printf("Write a number: ");
scanf("%d", &a);
printf("Your written number was: %d", a);
return 0;
}
Printf does not write "write a number" in console when i start the program but only after i already inserted the number and pressed enter.
I have already done some research and found out for this code:
setvbuf(stdout, NULL, _IONBF, 0);
when i paste this into my program it works as it should but i am wondering why do i have to do that?
when i paste this into my program it works as it should but i am
wondering why do i have to do that?
It's because printf() is usually line-buffered when attached to a terminal. So disabling the buffering with the call to setvbuf() makes stdio library to not buffer at all.
You can also use fflush(stdout); after the printf() call to flush out the buffered output. The same can be done with setbuf(stdout, NULL); as well.
You can also add a \n at the end of printf() statement to force the flushing. But this will work only if the output goes to a terminal device.
For example, if you do (on a unix-like system):
./a.out > output_file
then the \n will not flush the buffer.
Out of the two options (setbuf() and fflush()),fflush(stdout); is probably the better option in most cases. Since disabling the buffering completely can have negative impact on performance (which is the primary reason for buffering in the first place) whereas fflush() can be judiciously used at the right place when you think it's necessary.
printf has a buffer. It is a mechanism to make code run faster by not having to switch between the user context and the kernel context. To get over this you can tell the code to flush the buffer - i.e. send it to the operating system. This can be done by
fflush(stdout);
After a printf. If the printf contains a new line this is done automatically.
You probably want \n in each of those printf statements.
Add linefeed "\n" to your printf lines like so:
printf("Write a number: \n");

Wrong output when I run code in Eclipse Indigo CDT

I am using Eclipse Indigo CDT and just running simple code which is:
#include <stdio.h>
void main()
{
int num;
printf("enter no\n");
scanf("%d",&num);
printf("no is %d\n",num);
}
Opuput:
55
enter no
no is 55
But when I run this code it won't print enter no. Instead of that it waits to enter the number. After pressing some number it is printing enter no. What could be the reason?
That would depend on the flush scheme of standard out.
Traditionally, stdout is line buffered when connected to a terminal and page buffered when it's not connected to a terminal.
Apparantly, when you run your program in eclipse, standard out is page buffered.
You can overcome this by flushing stdout:
#include <stdio.h>
void main()
{
int num;
printf("enter no\n");
fflush(stdout);
scanf("%d",&num);
printf("no is %d\n",num);
}
It is good practice to flush a file handle whenever you expect the recipient of the information to respond. That way you can be sure that the recipient gets everything you have written regardless of the buffering of the file handle.

fflush() is not working in Linux

I used the fflush() in Linux GCC but it did not work. Are there any alternatives for that function? Here is my code:
#include<stdio.h>
void main()
{
char ch='y';
while(ch=='y')
{
int a;
printf("Enter some value:");
scanf("%d",&a);
fflush(stdin);
printf("Do you want to continue?");
scanf("%c",&ch)
}
The output that I got is:
Enter some value: 10
Then the program ends. That's all. What can I do in Linux? Is there an alternative function?
Don't use fflush, use this function instead:
#include <stdio.h>
void clean_stdin(void)
{
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
fflush(stdin) depends of the implementation, but this function always works. In C, it is considered bad practice to use fflush(stdin).
One that always works on Linux:
#include <termios.h>
#include <unistd.h>
void clean_stdin()
{
int stdin_copy = dup(STDIN_FILENO);
/* remove garbage from stdin */
tcdrain(stdin_copy);
tcflush(stdin_copy, TCIFLUSH);
close(stdin_copy);
}
You can use tcdrain and tcflush not only for in/out/err fd.
The behavior of fflush is not defined for input streams (online 2011 standard):
7.21.5.2 The fflush function
Synopsis
1
#include <stdio.h>
int fflush(FILE *stream);
Description
2 If stream points to an output stream or an update stream in which the most recent
operation was not input, the fflush function causes any unwritten data for that stream
to be delivered to the host environment to be written to the file; otherwise, the behavior is
undefined.
3 If stream is a null pointer, the fflush function performs this flushing action on all
streams for which the behavior is defined above.
Returns
4
The fflush function sets the error indicator for the stream and returns EOF if a write
error occurs, otherwise it returns zero.
I faced the same problem while working on LINUX and an alternative solution of this problem can be that you define a dummy character lets say char dummy;
and put a scanf() to scan it just before your actual input takes place. This worked for me. I hope it would work for you too.
fflush() doesn't do much for input streams but since scanf() never returns this doesn't matter. scanf() blocks because the terminal window doesn't send anything to the C program until you press Enter
You have two options:
Type 10 Enter
Put the terminal into raw mode.
The second option has many drawbacls like you will lose editing capabilities, so I suggest to read the input line by line.
You must include and use __fpurge(whatever you want) instead.
Salute from argentina
Use getchar() instead, after scanf
#include<stdio.h>
int main()
{
char ans='y';
int a;
while(ans=='y'||ans=='Y')
{
printf("Type a number:-");
scanf("%d",&a);
printf("square of number = %d\nwant to enter
number again(y/n)?\nANS=",a*a);
scanf("%s",&ans);//use %s in place of %c
}
return 0;
}
By using bzero(); system call in Linux we can flush the previous stored value.
Please read the manual page of bzero(); by typing in terminal man bzero.
try this example
#include<stdio.h>
#include<string.h>
int main()
{
char buf[]={'y'};
int num;
while(buf[0]=='y')
{
printf("enter number");
scanf("%d",&num);
printf("square of %d is %d\n",num,num*num);
bzero(buf, 1);
printf("want to enter y/n");
scanf("%s",&buf[0]);
}
return 0;
}

Resources