This question already has answers here:
Printing leading 0's in C
(11 answers)
Print numbers sequentially using printf with filling zeroes
(8 answers)
Closed 9 years ago.
I was trying to print a integer in c but those starting with zeroes causing me problem.
For example if no. is 01234 it is printing like 1234 instead of 01234.please tell how to do it in C
My problem is that there are 2 integers and I want to know whether first integer is in the starting of second or not.
for ex-
123 and
12345 "yes" because 123(first integer) is in the beginning of second integer(12345)
but in case
123 and
012345
it should print "no" because 123 in not in the beginnig of 0123345 but in c trailing zeroes get deleted and my program is printing "yes"
please tell what to do (note-no.of digits can vary in range of integer and 2nd integer is either equal or greater then 1st integer)
int i = 1234;
printf("%08d", i); // zero-pad to 8 places.
printf documentation
Working example
my suggestion would be , If you are taking the value from STDIN from the user.
Then if you want to use that value for printing purpose, then you need to store that integer with leading zeros into a string rather than an integer. Because leading zero has no meaning if you are storing that string value in an integer.
so %s in printf with retain the number of zeroes that user has enetered in that way.
#include <stdio.h>
#include <string.h>
#define N_DIGITS 64
main()
{
char a[N_DIGITS], b[N_DIGITS];
scanf("%s%s", a, b);
if(strncmp(a, b, strlen(a))==0)
puts("yes");
else
puts("no");
return 0;
}
Note that the length of digits is limited by value N_DIGITS.
The result is as below;
$ ./a.out <<<"123 12345"
yes
$ ./a.out <<<"123 012345"
no
Related
This question already has answers here:
Octal representation inside a string in C
(2 answers)
Closed 5 years ago.
#include<stdio.h>
#include<string.h>
int main() {
char a[100]="1234\0567"; //Answer: 6
int len=strlen(a);
printf("%d",len);
}
This code prints 6 as the answer. Shouldn't it print 4 since strlen returns the count until the null character is encountered?
However when a space is included between \0 and 5. It returns 4 as the answer
char a[100]="1234\0 567"; //Answer: 4
Am I missing something?
You first version has the octal number \056 not the \0 character
Edit:
in the similar situations use \000 octal sequence instead:
/* from your example*/ char a[100]="1234\000567";
The \056 is a single character, with the octal ASCII code (56)8, decimal - (46)10.
This question already has answers here:
Set variable text column width in printf
(2 answers)
Closed 6 years ago.
In C, as I understand so far, this would be correct:
printf("%10s\n", "This is C");
would return:
" This is C!"
(with the intentional space prior to the string; no quotations).
My question is can you replace the 10 specifying the length of the print using a variable? If so, how?
That's how:
printf("%*s\n", 10, "This is C");
The format changed from %10s to %*s. The printf() now would expect among the argument, before the string, an int with the width to pad the string to (the 10 in the example above; obviously could be a variable too).
To tell the printf() to pad the output to the left (instead of the default right) use the -: %-*s. (The output would change from " This is C" to "This is C ".)
To tell the printf() to take only few first bytes from the string, or if the string is not null-terminated, you can add .* to the format at the same place as the precision for floating point types. The printf() would print up to that number of characters, stopping at the first null character. Example:
int width = 10;
int chars = 4;
printf( "%-*.*s", width, chars, "This is C" );
would produce output "This ".
printf("\n%12.6f%12.6f%12.6f", R[1], LS[1], LAMBDA);
The R is an array of floats, LS is also an array of floats, and LAMBDA is a single float variable.
I'm trying to convert a program over to Java but I cannot figure out what this line is trying to do (I am not experienced in C at all).
The printf() function prints to stdout, which is usually the console, and uses a particular variable-replacement syntax in strings - what you're looking at is thus a format string. Breaking it down:
\n : newline
%12.6f : next variable,
width 12 -- Padded with spaces to make the string exactly 12 characters if it's not already
precision 6 -- Six digits after the decimal point
in decimal floating point format
+2 more iterations of this
The array lookup syntax is the same as in Java, so it's looking up the second (because zero-based indexing) element in R and LS.
It just print these value to stdout, in float number format with specified format.
More details can be found at printf().
Here is a tiny test program, and its output:
#include <stdio.h>
int main(int argc, char **argv) {
float R[2] = {1./7. * 10000, 2./7. * 10000};
float LS[2] = {3./7. *10000, 4/7. * 10000};
float LAMBDA = 5/7. *10000;
printf("BEFORE");
printf("\n%12.6f%12.6f%12.6f", R[1], LS[1], LAMBDA);
printf("AFTER\n");
}
BEFORE
2857.142822 5714.285645 7142.856934AFTER
So, a newline, then all on one line, with each number taking up 12 spaces, R[1], LS[1], and LAMBDA, printed to 6 digits of accuracy. Then, no newline, so they must want something else to happen on the line line after.
I'm trying to convert a long long integer to a string array with the 1's column in position 0 of the array, the 10's column in position 1, the 100's column in position 2, like this:
INPUT: 4444555566667777 -----> OUTPUT: [4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7]
To test my code, I wrote for my last line printf("%d\n",number_str[3]). I expected my program to output the value of position 4, "7". Instead, it output "52". Changing my last line to printf("%d\n",number_str[4]) yields "53" instead of "6", as I expected. Can anyone explain what's going on?
Surely 52 and 53 correspond to ASCII values, but then, how can I convert them to integers? Can I do this in line?
Where I'm headed with this part of my program is to add up all of the numbers in the 10's, 1,000's, 100,000's, 10,000,000's... columns. Every other digit in a base-10 credit card number. This is one step in my attempt at a Luhn validation.
// Libraries
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Program
int main(void)
{
// Get CC number
printf("Enter your credit card number: ");
long long number_ll = GetLongLong();
// printf("%lld\n", number_ll);
// Convert long long to string
char number_str[64];
sprintf(number_str, "%lld", number_ll);
// printf("%s\n", number_str);
// Get length of card number string
int cclength = strlen(number_str);
// Check the length of card number string
if ( ! (cclength == 13 || cclength == 15 || cclength == 16))
printf("INVALID\n");
else
printf("%d\n",number_str[3]);
To convert ascii into integer use
#include <stdlib.h>
int atoi(const char *str);
change this
printf("%d\n",number_str[3]);
to
char buf[2];
buf[0]=number_str[3];
buf[1]='\0';
printf("%d\n",atoi((const char*)buf));
Using "%d" on a char will print its ASCII code. Use "%c" to print itself.
And your string's order is reversed compared to your purpose. The rightmost digit(1's column) is at the tail of the string, and the leftmost one is in position 0.
So to print the number at position i (count from right to left), you should use:
printf("%c\n", number_str[cclength - i - 1]);
I'm going to go ahead and expand on my comment since I don't believe either of the other answers responded to your full question.
By reading the CC number into a long long, and then using sprintf to plug the number into a character array, I would say you're correctly getting the number into a form that you can use for validation. In fact, you can check the return value of sprintf to see whether or not it's a valid number (although a failure case would be unlikely since you're plugging in a long long.
Once you have the CC number in a character array, you know that each element of the array will contain one character, which corresponds to one digit in the CC number. It sounds like for your purposes, it's more useful for the values in the array to be the decimal values, rather than the ASCII values. Logically, this is the difference between the values '0' and 0. You can look up any ASCII chart to see the corresponding ASCII value for each character, but since characters can be manipulated just like integers, you can traverse the array:
for(i = 0; i < 64; i++) num_str[i] -= '0';
Note that this doesn't handle there being less than 64 characters or uninitialized values in the array after the CC number characters, so you'll need to modify it. What's important to realize is that you're just shifting the character values down by '0', which happens to have the integer value 48.
Once you do this conversion, printing out a value in the array with printf using %d as the format specifier will work like you expect; even though the array data type is char, each element may be printed as a decimal integer.
Once you've read the number into the char array and made the conversion, all you need to do is traverse the array again, performing whatever steps are involved in the CC Validation process. You may need to traverse the array in reverse if the validation method requires the digits to be in order.
I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to QString variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little 'printf primer' for Stackoverflow.
In the code, I came across this little gem,
printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g);
How will the variables a, b, c, d, e, f, g be formatted?
Danny is mostly right.
a. unsigned decimal, minimum 4 characters, space padded
b. floating point, minimum 16 digits before the decimal (0 padded), 1 digit after the decimal
c. hex, minimum 4 characters, 0 padded, letters are printed in upper case
d. same as above, but minimum 2 characters
e. e is assumed to be an int, converted to an unsigned char and printed
f. same as e
g. This is likely a typo, the 4 has no effect. If it were "%.4s", then a maximum of 4 characters from the string would be printed. It is interesting to note that in this case, the string does not need to be null terminated.
Edit: jj33 points out 2 errors in b and g above here.
#Jason Day, I think the 4 in the last %4s is significant if there are fewer than 4 characters. If there are more than 4 you are right, %4s and %s would be the same, but with fewer than 4 chars in g %s would be left justified and %4s would be right-justified in a 4 char field.
b is actually minimum 16 chars for the whole field, including the decimal and the single digit after the decimal I think (16 total chars vs 18 total chars)
Here's my printf primer:
http://www.pixelbeat.org/programming/gcc/format_specs.html
I always compile with -Wall with gcc which
will warn about any mismatches between the supplied
printf formats and variables.
#jj33, you're absolutely right, on both counts.
#include <stdio.h>
int main(int argc, char *argv[]) {
char *s = "Hello, World";
char *s2 = "he";
printf("4s: '%4s'\n", s);
printf(".4s: '%.4s'\n", s);
printf("4s2: '%4s'\n", s2);
printf(".4s2: '%.4s'\n", s2);
return 0;
}
$ gcc -o foo foo.c
$ ./foo
4s: 'Hello, World'
.4s: 'Hell'
4s2: ' he'
.4s2: 'he'
Good catch!
a. decimal, four significant digits
b. Not sure
c. hex, minimum 4 characters
d. Also hex, minimum 2 characters
e. 1 character
f. String of characters, minimum 4
What you really need is a tool which takes the format strings in printf() statements and converts them into equivalent QString based function calls.
Does anyone want to spend his Free Software Donation Time on developing such a tool?
Placeholder for URL to a Free Software hosting service holding the source code of such a tool