How can I print the 0 value in front of integer
if user enters 05 printing 05. %d just ignores the 0
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
x = 05;
printf("%d", x);
return 0;
}
output = 5
First of all, realize that constants with a leading 0 are interpreted as octal, not decimal. 05 and 5 are the same, but you'll have an issue with something like 09.
You can specify a minimum output field width like so:
printf( "%2d\n", x ); // minimum field width of 2, pad with blanks
or
printf( "%*d\n", 2, x ); // minimum field width of 2, pad with blanks
To pad with a leading 0, use
printf( "%02d\n", x ); // minimum field width of 2, pad with 0
or
printf( "%0*d\n", 2, x ); // minimum field width of 2, pad with 0.
Use the format specifier %02d:
#include <stdio.h>
int main(void)
{
int x;
x = 05;
printf("%02d\n", x);
return 0;
}
If a user can enter 05 or 5 and you want to distinguish between the two you need to read the input as a string instead. As mentioned by user3121023, note that integers with a leading zero are interpreted as octal numbers, for instance 010 equals 8.
Here is the full documentation of printf:
https://pubs.opengroup.org/onlinepubs/9699919799/
printf("%02d", x);
The zero represents how many digits will the zero padding be so if you wanted to do the same with 10 for example it should be 03 hope this helps.
If the user enters “05” and you read it using scanf with %d or something similar, the only result you will get from the scanf is the value five; there will be no indication whether the user entered “05” or “5”. If you need to know specifically what the user enters, you need to read the input as strings or characters.
If you use ”0” as the first digit of a constant in C source code, it introduces an octal constant, so that 010 represents eight.
If you want to print a leading “0” before a number, you can simply include it literally in the format string: printf("0%d", x);.
If you want to print the string with at least a certain number of digits, with as many leading zeros as necessary to give that many digits, you can use “0n” in the format specification, where “n” is the number of digits: printf("%02d", x);.
If you want to combine the above and print a zero in front of the number if and only if the user entered a zero in front of the number, you need to write source code that adjusts what is printed based on what was seen in input. (The easiest way to do this may be to record the characters the user types and just print those exactly.)
Related
I'm trying to write code that counts even digits (a typical beginner task)
What changes do I need to make in the code to get 2, for example, from the number 0011?
Is there a simple solution without additional libraries and complex loops?
#include <stdio.h>
int evensDigitsCount(int number);
int main()
{
int res = evensDigitsCount(0011);
printf("Counter: %d\n",res);
return 0;
}
int evensDigitsCount(int number)
{
int rem = 0;
int count = 0;
do{
rem = number % 10;
if(rem % 2 == 0 )
count++;
number = number / 10;
}while(number != 0);
return count;
}
“0011” is not a number. It is a numeral, which is a string of characters that represents a number.
In common human notation, “0011” is in decimal and represents the number eleven. However, in C source code, numerals starting with “0” (but not “0x” or “0X”) use octal, so “0011” represents the number nine.
Calling evensDigitsCount(0011) gives the number parameter of evensDigitsCount the value nine. It is just that abstract mathematical entity of nine; it does not have any digits or other characters representing it. (It is represented inside the computer with a string of bits, but that does not matter here, because the C source code you show operates on its value, not the bits that represent it.)
When the program executes rem = number % 10, number has the value nine, and the remainder of nine modulo ten is nine, so rem is set to nine. This is not even, so count++ is not executed.
Then number = number / 10; calculates nine divided by ten, rounded down (since number is positive) to an integer. This produces zero, so number is set to zero, and the loop ends.
To count the digits in a numeral, you must pass the numeral as a string, not a number. You could rewrite evensDigitsCount to have a parameter of const char *numeral, and then you could call it with evensDigitCount("0011"). Then the function could examine each character in the string to check whether it is one of the even digits, “0”, “2”, “4”, “6”, or “8”.
Your code is behaving correctly. 0011 is an octal literal for the decimal value 9, and your code is accurately reporting that, in base-10 (decimal), 9 has no even valued digits (the only digit is 9, and it's odd).
Your problem seems to be that you think 0011 remembers the digits it was typed with. It does not. In every way that matters, typing 0011 is the same as typing 9 in the same spot. If you want to preserve all the digits, including leading zeroes (which don't exist once the code is compiled), you need to work with strings (e.g. "0011"), not ints, and parse the digits as you go, rather than extracting them mathematically.
Alternatively, since you ignore odd digits, your existing code will work if you just shove an odd digit on the left side of any literal passed to it (preventing interpretation as octal and preserving the zeroes you expect to see), but that's only valid for literals you control, you couldn't reliably do it for data generate in other ways (which has no way of knowing how many leading zeroes "count").
Numbers starting with 0 are octal constants. So 0011 is octal representation for decimal 9.
Just leave off the leading zeros if you want decimal.
The other answers provided are all correct, explaining the "octal" interpretation of the digits in your OP.
This OP highlights the "unexpected" results when a beginner's knowledge is still growing. "Why does the compiler treat my values different from what I can clearly see in the source code?"
This suggests an interesting (and, perhaps, educational) digression; What if a program COULD examine its own source code?
Below is an attempt to provide an example of a program that does just that. The program reads lines from its own source code file until it finds "the interesting line", then, after some stepping closer to the interesting bit of that line (remembering that this is 'text'), a version of your function counts the number of even 'digits' until it reaches the end of those ASCII digits (the ')' of the function parameter list.)
The only "additional library" is the used everywhere C string library of functions. And these loops should not be too 'complex' to understand. This program makes use of "pointers to strings", a concept to be mastered early in one's learning.
#include <stdio.h> // FILE and printf()
#include <string.h> // str???() // additional library header
// function definitions ahead of "use" eliminates prototypes (for single sources)
// NB: function now "sees" value as a string, not a translated integer
int evensDigitsCount( char *str ) {
char *dgts = "0123456789", *p = NULL; // some variables
int count = 0;
printf( "Examining str: '%s'\n", str );
// step forward thru string as long as finding ASCII integers
// pointer arithemetic converts ASCII digit
// to index in ascending ASCII string of digits
// If index mod 2 has no remaider, then digit is even
// In C, true has the value 1 (false value is 0)
// Add 1 (or 0) to accumulator
for( ; ( p = strchr( dgts, *str ) ) != NULL; str++ )
count += (p - dgts)%2 == 0;
return count;
}
int main() {
// compiler "knows" this source filename.
// it replaces __FILE__ with the filename as a string
char *fname = __FILE__;
char buf[ 256 ]; // generous?
// to remember where target string located in line buffer (when found)
char *fncCall = NULL;
printf( "Examining file '%s'\n", fname );
// open THIS source file (text) for reading
FILE *ifp = fopen( fname, "r" ); // brevity. omitting checks
// read lines until target string found
while( !fncCall && fgets( buf, sizeof buf, ifp ) )
fncCall = strstr( buf, "= evensDigitsCount(0000121);" );
// NB: For this version, it is the line above
// that will be "found" as the 'target'
// (looking for itself in the text of this source code)
// Alternate processing could find the actual function invocation below
// This is an example of "program introspection" for demonstration purposes
fclose( ifp ); // no longer needed
// target not found... should never happen!, but...
if( !fncCall ) {
printf( "Cannot locate target string\n" );
return -1;
}
printf( "Found target: '%s'\n", fncCall );
// invoke (adapted) version of your function
// passing pointer to one-beyond the open parenthesis
int nEven = evensDigitsCount( strchr( fncCall, '(' ) + 1 );
printf( "Number of even digits found = %d\n", nEven );
return 0;
}
Output: The "broken lines" arise because fgets() leaves the LF at the end of the string buffer.
Examining file '.../StackOver.c' // shortened full name
Found target: '= evensDigitsCount(0000121);" );
'
Examining str: '0000121);" );
'
Number of even digits found = 5 // expected result!
Although this answer departs from your OP somewhat, it does show how you may be able to write a program that sees things your way (when you need to.)
#include <stdio.h>
void main()
{
int i = 0, k;
if (i == 0)
goto label;
for (k = 0;k < 3; k++)
{
printf("hi\n");
label: k = printf("%03d", i);
}
}
Can anybody explain how the output is 0 and not 000? When i run the program in devc++ it gives the output 000. But in most of the websites i found the right answer to be 0.
The proper output is 000.
The format specifier %03d contains the conversion specifier d, a field width of 3, and the flag 0. The d specifier means to print an int. The field width of 3 means that the value will be printed in a field at least 3 characters wide. The 0 flag means that any extra spaces in the field to print are padded on the left with a 0.
Any compiler that does not output this is non-conforming.
The output should be 000. %3d will print two spaces if i is 0: the %03d will print zeros instead of the spaces. The return value of printf is the number of characters that have been printed, so the loop that you've crashed into will terminate as k < 3 will be 0.
There's no undefined behaviour in the rather odd code you've presented. So if the leading two zeros are missing then the compiler and / or the runtime environment that you're using is defective.
I need to preserve any leading zeroes in the input, so I take the digits in as chars and then convert them back to integers using the ctoi() function, as shown in this code:
#include<stdio.h>
#define ctoi(a) a-'0'
int main() {
int n;
char ch;
scanf("%c",&n);
ch=ctoi(n);
printf("%d",n);
}
But that code didn't work. What is the problem?
Input:
001
0123
78
000123
Expected Output:
1
123
78
123
But I got:
1
1
7
1
when you store the number as an integer, you only store the actual number, not the formatting used to make that number. If you want to preserve the formatting as is you either need to store it as a string or some other means of storing the original formatting.
int n = 10; // only stores a number in memory
char text[10] = "00010"; // stores any text, but can not be used for number arithmetic as stored here
I don't understand how this printf() call is working to add together two numbers. Does the %*c have something to do with it?
//function that returns the value of adding two number
int add(int x, int y)
{
NSLog(#"%*c",x, '\r');
NSLog(#"%*c",y, '\r');
return printf("%*c%*c", x, '\r', y, '\r'); // need to know detail view how its working
}
for calling
printf("Sum = %d", add(3, 4));
Output
Sum=7
When passed to printf (or similar functions), %*c means you're passing two parameters instead of one. The first parameter specifies a field width, and the second a character (or string, int, etc.) to write out in that width of field.
printf returns the total number of characters written to the output stream.
A number after % specifies the field width; so %5c will print 4 spaces, followed by the character argument, giving a total of 5 characters.
* specifies that the field width is provided as an argument to printf. So this will print one field of x characters, followed by another of y characters. Each field consists of spaces followed by a carriage-return ('\r'), so there shouldn't be any visible output. printf returns the total number of characters printed - in this case, x+y.
i agree with leeduhem, it is extremely clever,
printf() return the number of character it printed.
For the argument, I think it is more easy to understand with an example:(Also you can see the width trick in here:
#include <iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int main() {
// your code goes here
int x = printf("%*c", 100, '\r');
printf("%d\n", x);
return 0;
}
x is whatever value you set to specific the width (in the eg, it's 100)
That means the width you specific is actually counted and return by the printf()
But I think this add() can only duel with positive numbers, if one of the number is <= 0, the method should fail, you may try add(-3,-4), in my own machine it still print 7...
Oh, this is clever.
return printf("%*c%*c", x, '\r', y, '\r');
On success, printf() will return how many character it printed, and "%*c", x, '\r' tell it to print x characters (x-1 spaces followed by one \r). Therefore, printf("%*c%*c", x, '\r', y, '\r') will return how many characters are printed, which is x+y.
See printf(3) for further details.
Note:
As pointed out by #shole, this int add(int x, int y) works only for both x and y are nonnegative integers. For example:
add(-1, 1) // gives 2 instead of 0
add(0, 1) // gives 2 instead of 1
It is a very trivial question but I don't know why I am not getting the correct output. Here is what I am trying to do:
char sendBuffer[1000];
int count=0:
while(count<10)
{
sendBuffer[0]=count;
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
printf(%s,sendBuffer);
count=count+1;
}
In the output, all buffer is printed correctly except the first index. I want 1,2,3 and so on to be printed at the start of the buffer but it does not work. Please Help
You need to convert that number into a character. A cheap way to do it is:
sendBuffer[0] = '0' + count;
is there anyway to display integers greater than 9
If you need that you'll want to shift to more elaborate schemes. For example, if you want to convert an integer 42 into the string "42" you can say:
#define ENOUGH ((CHAR_BIT * sizeof(int) - 1) / 3 + 2)
char str[ENOUGH];
snprint(str, sizeof str, "%d", 42);
Credit for ENOUGH goes to caf.
printf(%s,sendBuffer); should be printf("%s",sendBuffer);
Change
sendBuffer[0]=count;
to
sendBuffer[0]='0' + count;
i.e. convert the integer 0...9 to the characters '0' ... '9'
Also add a quote i.e. printf("%s",sendBuffer);
Quoted from the question:
In the output, all buffer is printed correctly except the first
index.i want 1,2,3 and so on to be printed at the start of the buffer
but it does not work. Please Help
I think her problem is that she does not get any output for the first line. That is because in the first iteration, count is 0, i.e. sendBuffer[0] is 0 which is the '\0' character. Hence the string is treated as empty.
You are trying to print the ascii characters corresponding to decimal values 0-9 which are non-printable characters. If you need to print decimal 0-9 then initialise count to 48 which is the ascii decimal code for '0' and change the condition in the while block to count < 58; 57 is the ascii deciaml code for '9'. See below:
char sendBuffer[1000];
int count=48:
while(count<58)
{
sendBuffer[0]=count;
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
printf(%s,sendBuffer);
count=count+1;
}
To convert an integer value to a char representation, add the value of the character '0':
sendBuffer[0]=count + '0';
Notice that's the character '0', not the number 0. This is because of how ascii values work. The char with a literal value of 0 is \0, the null terminator. Digit '0' has a literal value of 48, '1' 49 and so on.
This works for the digits 0-9. You can't put a char representation of a number bigger than that in a single char, obviously.
char sendBuffer[1000];
// take fixed stuff outside the loop
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
// it's best not to rely on order of ASCII values
for(char* numbers="0123456789"; *numbers!=0; numbers++){// use for loop for numbers
sendBuffer[0] = *numbers;
printf("%s",sendBuffer);
}