printf("Enter 'a' : "); runs 2 times after 1st loop

printf php
printf java
printf bash
printf python
printf linux
printf long
printf double
printf binary
int main (int argc, char *argv [])
{
     char a = 'v';

     for (int i = 0; a != 'x'; ) 
     {        
         printf("Enter 'a' : "); 
         scanf("%c",&a);
     }

     return 0;
}

I ran it and gave input k. When I hit enter after this , why my printf runs 2 times when loop runs second times?

To understand this behaviour, we can simulate step-by-step the execution.

printf("Enter 'a' : "); 
scanf("%c",&a); // User type in example 'a' and presses enter.

scanf "bufferize" a\n and places in a the value 'a'

The loop condition isn't satisfied, since 'a' == 'x' is false

printf("Enter 'a' : ");
scanf("%c",&a); // The buffer still contains `'\n'`

Since the buffer still contains unconsumed data, the next character ('\n') is placed in a and the loop continues.

The loop condition isn't satisfied, since '\n' == 'x' is false

printf("Enter 'a' : ");
scanf("%c",&a); // The buffer is empty now.

This gives you the illusion that the loop displays twice the printf, but in fact, the scanf kept reading the buffer without the need of user input.

If you enter more characters, in example qwerty, "Enter 'a' : " will be displayed 7 times, because "qwerty" contains 6 characters + '\n'


Note that using while (a != 'x') would suit better your needs than for (int i = 0; a != 'x'; )

C library function - printf(), 4) Writes the results to a character string buffer . At most buf_size - 1 characters are written. The resulting character string will be terminated with  Writes the C string pointed by format to the standard output ().If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.

When you use scanf and %c, it reads any character -- including the newline character you get when you press the ENTER key.

So if you run the program and type

a <Return>

you take two trips through the loop: one to read the 'a' and one to read the '\n'. If you type

<Space> <Space> a <Return>

it makes four trips through the loop. And if you type

x <Return>

it only makes one trip through the loop, because it notices you typed the 'x', and exits.

Things will become a little more clear if you print out each character you receive:

for (int i = 0; a != 'x'; )
{
    printf("Enter 'a' : ");
    scanf("%c",&a);
    printf("you typed %d =  %c\n", a, a);
}

When you see it printing

 you typed 10 =

that's one of the newlines. (The value of '\n' is 10 in ASCII.)

I said that %c reads any character -- but that's somewhat unusual. Most of scanf's other format specifiers -- %d, %f, %s, etc. -- skip over "whitespace" -- that is, spaces, tabs, newlines, and a few others. But %c does not skip over those, because its job is to read exactly one character, and someone thought you might want to use it to read whitespace characters, too.

printf format string, printf. (PHP 4, PHP 5, PHP 7). printf — Output a formatted string. Description ¶. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C and many other programming languages.The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such

For starters this loop

for (int i = 0; a != 'x'; ) 

does not make sense at least because the variable i is not used within the loop.

Also this prompt

printf("Enter 'a' : ");

only confuses users. You are asking the user to enter the character 'a' while the loop stops when the character 'x' is entered.

This call of scanf

scanf("%c",&a);

reads all characters including white-space characters. It is the reason why the loop iterates one more. You have to write

scanf( " %c", &c );
        ^^^

In this case white spaces will be skipped.

From the C Standard (7.21.6.2 The fscanf function)

5 A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read

The program can look the following way

#include <stdio.h>

int main(void) 
{
    char c;

    do
    {
        printf( "Enter a character ('x' - exit): " );
    } while ( scanf( " %c", &c ) == 1 && c != 'x' );

    return 0;
}

std::printf, std::fprintf, std::sprintf, std::snprintf, This volume of IEEE Std 1003.1-2001 defers to the ISO C standard. [Option End]. The fprintf() function shall place output on the named output stream. The printf()  printf() prototype int printf( const char* format, ); The printf() function writes the string pointed to by format to stdout. The string format may contain format specifiers starting with % which are replaced by the values of variables that are passed to the printf() function as additional arguments. It is defined in <cstdio> header file.

printf - Manual, The functions in the printf() family produce output according to a format as described below. The functions printf() and vprintf() write output to stdout, The writers of printf() thought of a lot of different types of variables, but if they didn’t think of it, then you’re out of luck. About the Book Author Stephen R. Davis is the bestselling author of numerous books and articles, including C# For Dummies .

fprintf, printf, snprintf, sprintf, printf formatting with Perl and Java. In this cheat sheet I'll show all the examples using Perl, but at first it might help to see one example using both  The power in printf() lies in its formatting string. That text can be packed with plain text, escape sequences, and conversion characters, which are the little percent goobers that insert values into the text output.

printf(3): formatted output conversion, Character and string arguments that are specified by using c and s are interpreted as char and char* by printf family functions, or as wchar_t and  C Tutorial – printf, Format Specifiers, Format Conversions and Formatted Output In this C programming language tutorial we take another look at the printf function. We will look at how to use format specifiers to print formatted output onto the screen.

Comments
  • There is no loop iteration condition.
  • @Ankit Bajpai: a != 'x' is the exit condition; there is no loop increment
  • Hmmm, I messed up the terms...
  • int i = 0; is redundant and can be dropped: for (;a != 'x';) {...} or, better, while (a != 'x') {...}
  • If I input 'spacebar' multiple times and hit enter , "Enter 'a' : " is printed out as many times as I input 'spacebar'. why?
  • Why giving a space before %c avoids the problem?
  • Because it consumes first a whitespace (in your case, '\n')
  • @user10056563 See my updated post.
  • Sorry I am new to programming. But why is scanf compared to 1 in 'while'?
  • @user10056563 It means that the function read successfully one item. Take into account that the user can interrupt the input. In this case the function will return EOF.