This question already has answers here:
Print part of a string in C
(4 answers)
Closed 9 years ago.
Is it possible in C to set a number of chars to be output from string?
char const *str = "abcdefgh";
printf("%???s", str);
What should be placed instead of ??? to output abc?
Yes, you could use a precision specifier, which would look something like this
printf("%.3s", str); // this prints "abc"
yes there is , you can use printf("%.3s" , str) , or printf("%.*s" , 3 , str);
printf has the following definition:
int printf ( const char * format, ... );
A format specifier follows this prototype:
%[flags][width][.precision][length]specifier
You can take a look here to get an overview about these specifiers.
.number
For s: this is the maximum number of characters to be printed. By
default all characters are printed until the ending null character is
encountered.
However, as written by Happy Yellow Face, printf("%.3s", str); works fine.
This question does say "set number of chars" and not "limit number of chars".
The 3 solutions presented do the second. This is apparent when str is small like "ab".
To "set" the number to 3 use
printf(">%3.3s<\n" , "abcdef");
printf(">%3.3s<\n" , "ab"); // right justify
printf(">%-3.3s<\n" , "ab"); // left justify
printf(">%*.*s<\n" , 3, 3, "ab"); // right justify
printf(">%*.*s<\n" , -3, 3, "ab"); // left justify
>abc<
> ab<
>ab <
> ab<
>ab <
> < added for display purpose only.
Related
This question already has answers here:
How to repeat a char using printf?
(12 answers)
Closed 2 years ago.
I want to print a char '*' repeatedly where I give the no. of times the asterisk should be repeated.
Example: count = 20 and I want to print ******************** using printf() and format specifiers.
There is certainly no way to achieve that using only format specifier. You could hide your loop in a macro maybe but you'll definitely need a loop somewhere.
You cannot do that with standard format specifiers provided by printf(). However, there's a hacky solution (assuming the maximum padding length is reasonable), if you are willing to waste some space to store a filler string in your program.
#include <stdio.h>
int main(void) {
const char *fill = "********************"; // 20 chars
printf("%.*s\n", 10, fill);
printf("%.*s\n", 15, fill);
int n = 20;
printf("%.*s\n", n, fill);
return 0;
}
This works using .* to provide the maximum length of the string to print as first parameter.
Output:
**********
***************
********************
NOTE: you will only get up to strlen(fill) characters of padding (20 in the above example), anything more and printf will stop at the \0 terminator of fill.
I hope this is what you are looking for:
#include <stdio.h>
int main()
{
printf("%.*s", 20, "********************************");;
return 0;
}
This question already has answers here:
How to compare strings in an "if" statement? [duplicate]
(5 answers)
Using the equality operator == to compare two strings for equality in C [duplicate]
(9 answers)
Closed 3 years ago.
I am writing a c program to print specific statements if current day is Friday using if-else statement. What is the error involved?
I've tried using integer values for the same code and it works, but when i equate n as Friday the output shows else part only.
char s[10]="Friday";
char n[6];
printf("Enter a day:\n");
scanf("%s",n); //n is string
if(n==s)
printf("Have a nice weekend!");
else
printf("Have a nice day!");
I expect the output for "Friday" to be "Have a nice weekend!", but the output is "Have a nice day!" for any input.
You should use a function like strcmp to compare char arrays in C.
if(strcmp(s, n) == 0) {
printf("Have a nice weekend!");
}
When you use the == operator you are comparing addresses (or sometimes pointers), not string literal values.
Also as pointed out above (pun intended) an array in C needs space for the null terminating character.
For starters you should enlarge the array becuase the string literal "Friday" can not fit into the array.
For example
char n[10];
Secondly instead of scanf use the standard function fgets because scanf such as it is written in your program is unsafe.
For example
fgets( n, sizeof( n ), stdin );
You can remove the trailing new line character the following way
n[ strcspn( n, "\n" ) ] = '\0';
To do that you have to include the header <string.h>.
In this statement
if(n==s)
there are compared addresses of first characters of the strings. You need to use standard string function strcmp to compare the strings themselves instead of the pointers. For example
if ( strcmp( n, s ) == 0 )
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *s = "Friday";
char day[10];
printf( "Enter a day: " );
fgets( day, sizeof( day ), stdin );
day[ strcspn( day, "\n" ) ] = '\0';
if ( strcmp( day, s ) == 0 )
{
printf( "Have a nice weekend!" );
}
else
{
printf( "Have a nice day!" );
}
return 0;
}
Its output might look like
Enter a day: Friday
Have a nice weekend!
This question already has an answer here:
What is the meaning of "%-*.*s" in a printf format string?
(1 answer)
Closed 3 years ago.
I don't know how this code is working?
#include<stdio.h>
int main()
{
char *s = "PRO coder";
int n = 7;
printf("%.*s", n, s);
return 0;
}
The result I am getting is "PRO cod"
printf format string %.*s takes two arguments, * for the number and finally s for a string, so it prints the first 7 characters of the string pointer s. In general, anytime there is a number, you may use * instead to read it as an argument.
%7s would print seven characters or more if the string were longer, while %.7s would print up to seven characters. So sometimes one would write "%*.*s", 7, 7, s to print exactly 7 characters.
This question already has answers here:
Keep Leading zeros C
(2 answers)
keeping leading zeros in C [duplicate]
(3 answers)
Closed 4 years ago.
I am wondering as to why when converting strings to int with either atoi or strtol it does not print the number 0 if its the first index, take this code for example
char s[] = "0929784";
long temp = strtol(s, NULL, 10);
printf("%li", temp);
OUTPUT: 929784
is there a way to have the 0 print?
Use
char s[] = "0929784";
size_t len = strlen(s);
long temp = strtol(s, NULL, 10);
printf("%0*li", (int) len, temp);
Details are here.
A more subtle and even safer approach would be:
char s[] = "0929784FooBarBlaBla";
char * endptr;
long temp = strtol(s, &endptr, 10);
printf("%0*li", (int) (endptr - s), temp);
More details are here.
printf will print the long in the best way possible, and that includes dropping any leading zeros.
For example, if someone asks you to write your age, you wouldn't write 028 if you were 28 would you? Even more sinister in C, a leading 0 denotes an octal constant, so actually 028 makes no sense as a number in C. Formally 0 is an octal constant although that, of course, doesn't matter.
An int basically stores leading zeros. The problem that you are running into is that you are not printing the leading zeros that are there. (source)
printf manual:
0 A zero '0' character indicating that zero-padding should be used
rather than blank-padding. A '-' overrides a '0' if both are used;
So use:
printf("%0*li", (int) strlen(s), temp);
Yes. Try
printf("%07li", temp);
This following code:
printf("%d. %-10s:", 1, "Test");
produces this output:
1. Test :// 14 characters long
I would like the output length of the entire format `%d. %-10s:" to be exactly 10 characters like this:
1. Test: // 10 characters
Note:
The numbers vary in length, it could be 1 or 100, so I can't deduce it's length from the output.
How can I do that?
You need to use two steps:
char buffer[20];
snprintf(buffer, sizeof(buffer), "%d. %s:", 1, "Test");
printf("%-*s", 10, buffer);
The snprintf() operation give you a string 1. Test: in buffer; note that it includes the : in the output, and assumes no trailing blanks on the string "Test"). The printf() operation formats the string left justified (-) in a length of (at least) 10 (the * in the format and the 10 in the argument list) onto standard output. Presumably, something else will appear after this output on the same line; otherwise, there's no obvious point to the blank padding.
For full information, see:
snprintf()
This covers the basic operation of the *printf() family of functions (but does not list the interfaces to the v*printf() or *wprintf() families of functions).
The code in the question and in the answer above is all done with constants. A more realistic scenario would be:
void format_item(int number, const char *text, int width)
{
char buffer[width+1]; // C99 VLA
snprintf(buffer, sizeof(buffer), "%d. %s:", number, text);
printf("%-*s", width, buffer);
}
Note that this code truncates the formatted data if the number plus the string is too long. There are ways around that if you work a bit harder (like adding more than 1 to width in the definition of buffer — maybe add 15 instead of 1).
You might write:
format_item(1, "Test", 10);
or:
char *str_var = …some function call, perhaps…
int item = 56;
format_item(++item, str_var, 20);
etc.