can we use printf statement inside printf() function in C language - c

is the following statement correct in C?
printf(" the string is %s", printf("xyz"));
I mean, is it possible to use 1 printf statement inside printf function?
if possible then please send the proper syntax for that expression.

printf returns the number of characters printed, so the above statement would be wrong as your formatstring tries to print a string.
You could do it like this though:
printf("characters printed: %d", printf("xyz"));
If you want to output the result of a formatted string, you would have to use snprintf first, printing it to an array, which in turn you can use to print as a string then.
Example:
char s[100];
snprint(s, sizeof(s), "My string %d", 3);
printf(" the string is %s", s);

What printf does is just push characters to the buffered output stream. print returns:
On success, the total number of characters written is returned.
If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.
If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
so if you are looking to print any of those out, you can with that second printf. But it does not return a string, those characters are in the buffered output stream until one of these happen: program's termination, a '\n' is encountered, buffer is full, or a command like ffslush() is called.

This statement is not correct but, you can use printf within printf.
Upon successful return, printf functions return the number of characters printed (not including the trailing '\0' used to end output to strings).
you can use like:
printf(" the string is %d", printf("xyz"));

Syntax :-
printf ("Your String Length :: %d",printf("TestString"));
1) First it will execute inner printf
2) inner printf return with the string length.
3) that is used in outer printf with %d specifier.

It's pretty simple.
First printf() represent the main value, then rest of printf() count the number of print value.
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int i = 43;
printf("%d", printf("%d", printf("%d", printf("%d", i))));
getch();
}

Related

Format Specifiers in C and their Roles?

wrote this code to "find if the given character is a digit or not"
#include<stdio.h>
int main()
{
char ch;
printf("enter a character");
scanf("%c", &ch);
printf("%c", ch>='0'&&ch<='9');
return 0;
}
this got compiled, but after taking the input it didn't give any output.
However, on changing the %c in the second last line to %d format specifier it indeed worked. I'm a bit confused as in why %d worked but %c didn't though the variable is of character datatype.
Characters in C are really just numbers in a token table. The %c is mainly there to do the translation between the alphanumeric token table that humans like to read/write and the raw binary that the C program uses internally.
The expression ch>='0'&&ch<='9' evaluates to 1 or 0 which is a raw binary integer of type int (it would be type bool in C++). If you attempt to print that one with %c, you'll get the symbol table character with index 0 or 1, which isn't even a printable character (0-31 aren't printable). So you print a non-printable character... either you'll see nothing or you'll see some strange symbols.
Instead you need to use %d for printing an integer, then printf will do the correct conversion to the printable symbols '1' and '0'
As a side-note, make it a habit to always end your (sequence of) printf statements with \n since that "flushes the output buffer" = actually prints to the screen, on many systems. See Why does printf not flush after the call unless a newline is in the format string? for details
In a memory, int take 4 bytes of memory you are trying to storing the int values in a character which will return the ascii value not a int value in %c if you are using a %d which will return the int value which are storing in a memory of 4 bytes memory.

What is the output of: printf("%d\n",scanf("%d",&i))?

What is the output of this code if I input 25 to scanf()? I run this program, the output is 1 but I don't understand why? Can anyone explain?
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
printf("%d\n",scanf("%d",&i));
return 0;
}
scanf() returns the number of arguments successfully assigned. In your case, scanf only has one directive which has a respective argument to be assigned, so it returns 1 if the input conversion was done successfully.
1 is given now as argument to printf, which prints 1 into the output.
With the premise that the scanf() conversion was successfully,
printf("%d\n", scanf("%d",&i));
is basically equivalent to
printf("%d\n", 1);
Going straight forward
int i = 0, j = 0;
printf("%d\n", scanf("%d %d", &i, &j));
with the input of
25(enter)
50(enter)
and both conversions done successfully, would gave you the output 2 and
printf("%d\n", scanf("%d %d", &i, &j));
would basically be equivalent to
printf("%d\n", 2);
Side Note:
The return value of scanf() should always be checked by the algorithm but it is more an objective to the program to see if an input failure occurred than to diagnose it directly to the user.
These functions (scanf family) return the number of input items successfully matched and assigned.
So in this case it can return 1 if the scan was successful or 0 if not. If there is an error in the input stream it can also return EOF
Scanf is a basic function in C language.Since every function return a type of value or null,Scanf function returns numbers of inputs scanned successfully.
For Example: Scanf("%d%d") scans for 2 inputs, so it returns value 2.
Scanf("%f%d%d%d") scans for 4 inputs, so it returns value 4.
&variable_name is used to store the scanned value in the variable by using address-of operator.For scanning string, &-address-of operator can be neglible.
Example scanf("%s",variable)
Printf is a function which returns number of characters printed.It can be used with format specifer like %d,%f etc.
In the above program
printf("%d\n",scanf("%d",&i));
Scanf is first executed by scanning one integer input as %d is specified and stored in the variable of type int. Scanf returns value 1 since it is scanning only one input.
Printf function prints the value 1.Printing value does not depend upon input value.It depends only on number of inputs , scanf is scanned successfully.
you are outputting the scanf function which returns the variable numbers not the value in i.

Scanf changing the input in C

I have a fairly basic problem but I can't manage to solve it.
I'm trying to get an input from a user like this :
int main() {
char coord[2];
fflush(stdin);
scanf("%c", coord);
}
When i'm trying this code with printf("%c", coord);, it displays a completely different string from what I typed. For example, if I type "g6", it prints "Ê". I really have no clue why it's happening.
Thanks for helping me !
If you want to get string(char array) from user you should do this :
scanf("%s",coord);
%c is for single char
First of all avoid using fflush (stdin);. Standard input flashing is undefined behavior, according to C standard, and may lead to big issues .
Then, you are trying to get an input string using %c format, that is supposed to acquire a single character. Furthermore, your coord array has not enough room for the string terminator character (\0).
The format to be used in order to acquire a string with scanf (and to print it with printf) is %s:
int main() {
char coord[3] = {0};
scanf("%2s", coord);
printf ("%s\n", coord);
}
The "2" added to the format makes sure that at most two characters are read (exactly those you can have in you string array without overwriting the last character).
For starters this statement
fflush(stdin);
has undefined behavior and shall be removed.
The conversion specifier %c of printf expects an argument of the type char while you are passing an expression of the type char * to which the array designator is implicitly converted
printf("%c", coord);
you have to write either
printf("%c", *coord);
or
printf("%c", coord[0]);
Pay attention to that using this call of scanf
scanf("%c", coord);
you can enter only a single character. You can not enter a string.
If you want to enter a string in the array coord that has only two elements then you have to write
scanf( "%1s", coord);
In this case the array will be filled with a string of length equal to 1.
In this case you can output it like
printf("%s", coord);
If you want to enter a string like this "g6" then you have to declare the array like
char coord[3];
and write the following call of scanf
scanf( "%2s", coord);
The line char coord[2]; declares coord as an array of characters (also known as a "string"). However, the %c (in both scanf and printf) reads/writes a single character.
For strings, you need to use the %s format.
Also, if you want to store/read/print the string, "g6", you will need to allocate (at least) three characters to your coord array, as you must terminate all C-strings with a nul character.
Furthermore, calling fflush on the stdin stream is not effective (actually, it causes undefined behaviour, so anything could happen) - see here: I am not able to flush stdin.
So, a 'quick fix' for your code would be something like this:
#include <stdio.h>
int main()
{
char coord[3]; // Allow space for nul-terminator
// fflush(stdin); // don't do it
scanf("%2s", coord); // The "2" limits input to 2 characters
printf("%s\n", coord);
return 0; // ALways good practice to return zero (success) from main
}

How does a scanf() inside printf() work?

#include<stdio.h>
int main(){
int n;
printf("%d\n",scanf("%d",&n));
return 0;
}
I wonder why the output of this program is always '1' ?!
What's actually happening here ?
I suspect you wanted to use
int n;
scanf("%d", &n);
printf("%d\n", n);
but what you wrote is equivalent to
int n;
int num = scanf("%d", &n); // num is the number of successful reads.
printf("%d\n", num);
The program is just about exactly equivalent to
#include <stdio.h>
int main() {
int n;
int r = scanf("%d", &n);
printf("%d\n", r);
return 0;
}
So if you run this program, and if you type (say) 45, then scanf will read the 45, and assign it to n, and return 1 to tell you it has done so. The program prints the value 1 returned by scanf (which is not the number read by scanf!).
Try running the program and typing "A", instead. In that case scanf should return, and your program should print, 0.
Finally, if you can, try running the program and giving it no input at all. If you're on Unix, Mac, or Linux, try typing control-D immediately after running your program (that is, without typing anything else), or run it with the input redirected:
myprog < /dev/null
On Windows, you might be able to type control-Z (perhaps followed by the Return key) to generate an end-of-file conditions. In any of these cases, scanf should return, and your program should print, -1.
#jishnu, good question and the output which you're getting is also correct as you are only reading one value from standard input (stdin).
scanf() reads the values supplied from standard input and return number of values successfully read from standard input (keyboard).
In C, printf() returns the number of characters successfully written on the output and scanf() returns number of items successfully read. Visit https://www.geeksforgeeks.org/g-fact-10/ and read more about it.
Have a look at the following 2 code samples.
Try the below code online at http://rextester.com/HNJE76121.
//clang 3.8.0
#include<stdio.h>
int main(){
int n, n2;
printf("%d\n",scanf("%d%d",&n, &n2)); //2
return 0;
}
In your code, scanf() is reading only 1 value from the keyboad (stdin), that is why output is 1.
//clang 3.8.0
#include<stdio.h>
int main(){
int n;
printf("%d\n",scanf("%d",&n)); //1
return 0;
}
In your program scanf returns 1 when successfully some value is taken by scanf into n and that is why you are always getting 1 from your printf("%d\n",scanf("%d",&n));.
You should modify your code like following
#include<stdio.h>
int main(){
int n;
scanf("%d",&n);
printf("%d\n",n);
return 0;
}
In man scanf,
Return Value
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
In your program, it just match 1 input, so the function scanf will return 1, if you input an legal value that can match a %d, else it will return 0.
In your situation, you might always satisfy this requirements, so it always return 1.
scanf returns the number of successful conversion and assignments. In your case, you're only scanning for one argument, so scanf will either return a 1 on success, a 0 on a matching failure (where the first non-whitespace input character is not a decimal digit), or EOF on end-of-file or error.
When you call printf, each of its arguments is evaluated and the result is passed to the function. In this case, evaluation involves calling the scanf function. The value returned by scanf is then passed to printf.
It's essentially the same as writing
int count = scanf( "%d", &n );
printf( "%d\n", count );
For giggles, see what happens when you enter abc or type CtrlD (or CtrlZ on Windows).
Note that printf also returns a value (the number of bytes written to the stream), so you can write something ridiculous1 like
printf( "num bytes printed = %d\n", printf( "num items read = %d\n", scanf( "%d", &n ) ) );
Joke. Don't do that.
scanf returns number of successful conversions.
Try changing your scanf to as shown below....
you will notice printing 2 after inputting two valid integers.
int n1 =0;
int n2 =0;
int i = scanf("%d %d",&n1,&n2);
In C programming, scanf() takes the inputs from stdin() which is the keyboard and returns the number of successful inputs read
and printf() returns the number of characters written to stdout() which is the display monitor.
In your program scanf() is reading only one input which is getting returned and is printed by printf(). So, whatever may be the input the output is always 1 as it is reading only one input.
Here take a look at this C program:
#include<stdio.h>
int main(){
int n, n2;
printf("%d\n",scanf("%d %d",&n,&n2));
return 0;
}
It takes input or reads two integers from stdin() using scanf(), so the output will always be 2.
**Note: The output is 0 if your input is not integer, as it reads integer only.
The documentation of scanf() says the return value is:
Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.
The code you would instead want is:
#include<stdio.h>
int main(){
int n;
scanf("%d",&n);
printf("%d\n",scanf("%d",&n));
return 0;
}
If you use this code as an example,
It shows : warning: implicit declaration of function 'printf' [-Wimplicit-function declaration]
int main()
{
char b[40];
printf(" %d", scanf("%s", b));
getchar();
}
Return value : -1
Outputs of the functions like printf and scanf can be use as a parameter to another function.
scanf() is a function which is integer return type function. It returns total number of conversion characters in it. For ex if a statement is written as :
int c;
c=scanf("%d %d %d");
printf("%d",c);
Then output of this program will be 3.
This is because scanf() is integer return type function and it returns total no of conversion characters, thus being 3 conversion characters it will return 3 to c.
So in your code scanf() returns 1 to printf() and thus output of program is 1.
This is because if more than one statement are used in printf() execution orders starts from right to left.
Thus scanf() is executed first followed by printf().

printf() with %c format code not printing what I expect

#include <stdio.h>
int main ( ) {
int n;
n = 0;
printf ("%c\n", n);
return 0;
}
so that's my code, but when i print it, it just prints a blank space. Shouldn't it print 0?
Change %c by %d:
printf ("%d\n", n);
n is integer type so try to print it as..
printf("%d\n",n);
and if u use %c then its printing first byte's related char in ASCII table .
If you need to display 0 without changing the printf statement, the way to do it is to do
n = '0';
or
n = 48;
Take a look at Ascii Table, to see the ascii value of 0.
Printf Writes the C string pointed by format to the standard output (stdout). 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.
Here you are Using wrong format specifier to print your value. %c used for printing variables of type char(character) . Use %d for int(integer).
Try this Link

Resources