What is the use of * in printf? - c

I have a this code:
#include <stdio.h>
#include <conio.h>
void main()
{
int n = 5;
clrscr();
printf("n=%*d", n);
getch();
}
The output which I got is: n= 5. Why is there a space? How is it generated? What is the use of * in the code?

When in doubt, read the docs:
*:
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
However, you appear to be using it wrong. The proper way to use it would be like this:
printf("n=%*d", 2, n);

It is clearly mentioned in the C Manual.
The answer is already given by Richard J. Ross III. Just quoting again what is said from the manual.
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
Consider this code:
#include<stdio.h>
main()
{
int a,b;
float c,d;
a = 15;
b = a / 2;
printf("%d\n",b);
printf("%3d\n",b);
printf("%03d\n",b);
c = 15.3;
d = c / 3;
printf("%3.2f\n",d);
}
The output would be:
7
7
007
5.10
You can see here, how the printf function can be used for formatting output. Hope it helps. :)

With this *, you can set the width of your print with a variable.

Related

what is meaning of %5d%*.*f in c language

#include <stdio.h>
int main()
{
int val =10;
float val1 = 56.40;
printf("%d%*.*f", val,val,val-8,val1);
}
output is 10 56.40
what is actual menaing of %5d%*.*f
#include <stdio.h>
int main()
{
int val =10;
float val1 = 56.40;
printf("%d%f", val,val,val-8,val1);
}
output is 100.000000
why output is getting different by just outting %d%f ?
Code containing %d%f code, which giving output as 100.0000
Code containing %d%*.*f code, which giving output as 10 56.40
%5d means print an int with a minimum field width of 5. The the value isn't 5 characters wide it will be left padded with space. You either can't tell or you didn't paste in the spaces in your example output.
%*.*f means print a float with a minimum field width and precision (digits after the .) provided as arguments as signified by the *. In this case field width is val and precision val-8.
Your 2nd code sample is simply incorrect usage. You claim to pass a int and float but pass in 3 int and a float.

Expected Expression with square roots

#define PI = 3.141593
#define G = 6.67259E-11
#define g = 9.80665
#define M = 5.972E+24
#define r = 6378000
#define h = 220
#include <stdio.h>
#include <math.h>
int main(void)
{
int value;
value =sqrt((G/M)/(r+h))
printf("This is the tangential speed:") value;
return 0;
}
I am very new to coding, and my program is giving me several errors in code blocks, can anyone give me some guidance?
Remove the = from all the #define statements. They are preprocessor macro definitions, not assignment statements, and they do not use equal signs.
Change int value to double value, to use floating-point instead of integers.
Add a ; after value =sqrt((G/M)/(r+h)). Statements in C generally end with a semicolon.
Change printf("This is the tangential speed:") value; to printf("This is the tangential speed: %g.\n", value);. printf is a function call, not a statement, so you pass everything it needs inside a set of parentheses. The string is a format string; it contains both literal text you want printed and conversion specifications like %g that tell it to convert an argument to a string. %g tells it to convert a double argument to a general floating-point display form.
I see two problems:
Smallest problem, but might be significant, is that I assume you want value to be a float or double instead of an int, thus replace
int value;
by
float value;
The print statement is incorrect:
printf("This is the tangential speed:") value;
Assuming value is a float, change it to
printf("This is the tangential speed: %f\n", value);
\n makes a new line.
And of course don't forget the remark by chux.

Take a character from a string and convert it to int in c

I'm new to c and trying to write a console application that takes the time signature and BPM information from a user's musical project and returns the length of one bar in seconds.
I want to take the user input string for time signature (example: "4/4"), isolate the first character (a numeral representing the number of beats per bar), and transform it into an integer to be used in the calculation.
The two methods I've tried,
int beatsPerBar = timeSignature[0];
and
int beatsPerBar = atoi(timeSignature[0])
both return the same error: "subscripted value is neither array nor pointer nor vector".
How do I correctly change the variable type of this character?
EDIT:
Using #R-Sahu 's suggestion. The code below compiles and builds with no errors or warnings.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char timeSignature[4];
int BPM;
printf("Enter the working time signature of your project:");
scanf("%s",&timeSignature[4]);
int beatsPerBar = timeSignature[0]-'1';
printf("Enter the beats per minute:");
scanf("%i",&BPM);
printf("%i\n", beatsPerBar);
return 0;
}
However, when I test the code with the following values
timeSignature = "4/4"
BPM = 180
I get a resulting integer of -47 (calculator check says it should be returning 45).
What am I doing wrong? Clearly my understanding of encoding and the integers used to represent character values isn't where it should be. Can anyone share links to broad tutorials on this subject?
Use of
int beatsPerBar = atoi(timeSignature[0])
should result in a compiler error. The input argument type of atoi is char const*, which timeSignature[0] is not.
int beatsPerBar = timeSignature[0];
is syntactically right but not semantically. That will set the value of beatsPerBar to the integer value used to represent the character 4. If your platform uses ASCII encoding, that value is 52.
You should use:
int beatsPerBar = timeSignature[0] - '0';
to get the number 4 assigned to beatsPerBar.
If you want to be more careful, which you should, you can add the following check.
int beatsPerBar = 0;
if ( isdigit(timeSignature[0]) )
{
beatsPerBar = timeSignature[0] - '0';
}
else
{
// Deal with error.
}
As #r-sahu said:
The input argument type of atoi is const char *
So if you still want to use atoi you can convert the char to a string then use atoi as follows (for example):
if (isdigit(timeSignature[0]))
char dig[2]= {timeSignature[0],'\0'};
int beatsPerBar = atoi(dig);
No need to use atoi, you can simply convert a char to int. For instance
int beatsPerBar = timeSignature[0] - '0';

Unexpected behavior of printf() in C [duplicate]

This question already has answers here:
what does the - operator do with char *?
(4 answers)
Closed 9 years ago.
#include <stdio.h>
int main()
{
short int a = 5;
printf("%d" + 1, a);
return 0;
}
The code prints the alphabet enclosed in quotes in printf irrespective of the value and type of variable a. If any other number is added except 1 nothing gets printed.
Why is it so?
Not sure, I would expect it to print just d, of course. That's what happened when I tested it.
If you add more than 1 (or 2) all bets are off and you're getting undefined behavior for passing a random pointer instead of a valid formatting string.
On compiling the above code, you should get a warning like:
[Warning] too many arguments for format [-Wformat-extra-args]
Now remove the printfs argument a.
printf("%d" + 1);
This will print d.
100 101
% d
^
|
Here is the starting address of the string.
%d is a string and its starting address is 100. "%d" + 1 will give you the address 101.
Why you want to do this?
if you want you can do like
do like
printf("%d", a+1);
Try this and you'll understand what unwind is trying to make you understand
#include <stdio.h>
int main()
{
short int a = 5,b = 4;
printf("%d %d" + 4, a,b);
return 0;
}
OUTPUT: d
Since it takes the 4th character inside the double quotes in printf() statement..
If number is 3
OUTPUT: 5
If number is 2
OUTPUT: 5
If number is 1
OUTPUT: d

strcspn() stopping at a period

I'm writing a function that should parse a string containing a description of a dice roll, for instance "2*1d8+2". I extract the four values OK when they are integers, but I want to be able to use floats as well for the multiplier and the addition at the end. Things get nasty when I try to parse such a string: "1.8*1d8+2.5".
I have determined that the problem is with the function strcspn. I ask it to parse the input string s (which contains the dice string) and stop at either an asterisk or an 'x':
const char * s = "1.8*1d8+2.5";
size_t l = strcspn(s,"*x");
The function should return 3, as the asterisk is at the 4th position. However, it seems to stop on the decimal separator (period) and returns 1.
It's not that I can't continue writing my function without this, as there are other ways to get things done, but still I'm curious why such a thing would happen. Has anyone ever encountered this problem before?
[EDIT]
Nevermind, I've found the answer, and it was my stupidity rather than the compiler playing tricks on me. I used this code:
if (l = strcspn(s,"*x") < strlen(s)) {
...
which returned 1 (or true) because strcspn(s,"*x") < strlen(s) evaluates to true - and was assigned to the l variable. I should have added parentheses:
if ((l = strcspn(s,"*x")) < strlen(s)) {
...
Thanks for your answers nonetheless, particularly #sleske, who made me analyse my code more deeply (which led to finding the answer).
There must be an error somewhere else. I wrote a test program:
#include <stdio.h>
#include <string.h>
void main(){
const char * s = "1.8*1d8+2.5";
size_t l = strcspn(s,"*x");
printf("l: %d\n", l);
}
and compiled it with gcc on Linux. On my system, it outputs "3".
Please post a complete, working example that exhibits the problem. Then we'll see...
Your code works just as you posted it for me1.
#include <stdio.h>
#include <string.h>
int main(void) {
const char * s = "1.8*1d8+2.5";
size_t l = strcspn(s,"*x");
printf("%zd (%.*s)\n", l, (int)l, s);
return 0;
}
so ross$ ./a.out
3 (1.8)
1. Mac OS X 10.6.4
I'd use sscanf instead of manually finding stop points and parsing myself. You can get your integers and floats easily out of the string with that.
This code:
#include <stdio.h>
#include <string.h>
int main(void)
{
const char * s = "1.8*1d8+2.5";
size_t l = strcspn(s,"*x");
printf("<<%s>> %zd <<%s>>\n", s, l, s+l);
return 0;
}
produces this answer on MacOS 10.6.4 (GCC 4.5.1):
<<1.8*1d8+2.5>> 3 <<*1d8+2.5>>
If your compiler and library does not produce the same answer, get a fixed/upgraded version of the software.
(NB: The 'z' modifier in the printf() format string is a C99 feature - it indicates that the type of the parameter is size_t.)

Resources