In this code what is the role of the symbol %3d? I know that % means refer to a variable.
This is the code:
#include <stdio.h>
int main(void)
{
int t, i, num[3][4];
for(t=0; t<3; ++t)
for(i=0; i<4; ++i)
num[t][i] = (t*4)+i+1;
/* now print them out */
for(t=0; t<3; ++t) {
for(i=0; i<4; ++i)
printf("%3d ", num[t][i]);
printf("\n");
}
return 0;
}
%3d can be broken down as follows:
% means "Print a variable here"
3 means "use at least 3 spaces to display, padding as needed"
d means "The variable will be an integer"
Putting these together, it means "Print an integer, taking minimum 3 spaces"
See http://www.cplusplus.com/reference/clibrary/cstdio/printf/ for more information
That is a format specifier to print a decimal number (d) in three (at least) digits (3).
From man printf:
An optional decimal digit string
specifying a minimum field width. If
the converted value has fewer
characters than the field width, it
will be padded with spaces on the left
(or right, if the left-adjustment flag
has been given) to fill out the field
width.
Take a look here:
Print("%3d",X);
If X is 1234, it prints 1234.
If X is 123, it prints 123.
If X is 12, it prints _12 where _ is a leading single whitespace character.
If X is 1, it prints __1 where __ is two leading whitespacce characters.
An example to enlighten existing answers:
printf("%3d" , x);
When:
x is 1234 prints 1234
x is 123 prints 123
x is 12 prints 12 with an extra padding (space)
x is 1 prints 1 with two extra paddings (spaces)
You can specify the field width between the % and d(for decimal). It represents the total number of characters printed.
A positive value, as mentioned in another answer, right-aligns the output and is the default.
A negative value left-aligns the text.
example:
int a = 3;
printf("|%-3d|", a);
The output:
|3 |
You could also specify the field width as an additional parameter by using the * character:
int a = 3;
printf("|%*d|", 5, a);
which gives:
| 3|
It is a formatting specification. %3d says: print the argument as a decimal, of width 3 digits.
Literally, it means to print an integer padded to three digits with spaces. The % introduces a format specifier, the 3 indicates 3 digits, and the d indicates an integer. Thus, the value of num[t][i] is printed to the screen as a value such as " 1", " 2", " 12", etc.
2/3 or any integer is padding/width .it means ex for 3 ,minimum 3 space if we print a=4 then it print like 4,here two space left before 4 because it is one character
Related
I have a very strange question which stems from a bug of a C++11 program I have been writing.
See the following code:
long long a[1000];
int main(int argc, char * argv[]) {
for(long long i = 0; i < 300; ++i) {
scanf("%lli", &a[i]);
std::cout << a[i] << std::endl;
}
return 0;
}
Trying the inputs 1, 2 etc we get outputs 1\n, 2\n, etc. like expected. This also works for inputs like 001 where we get 1\n, 0004 where we get 4\n.
However when the digit after the leading zeros is an 8 or 9, the scanf() reads the leading zeroes first, then reads the digits after.
For example:
Input: 0009, output: 000\n9\n.
Input: 08, output 0\n8\n.
Input: 00914, output 00\n914\n.
I've done some testing and for these cases it seems the scanf() reads the leading zeros first, and the remaining digits are left in the buffer, which are picked up on the second run of the loop.
Can someone hint at what is going on?
I am using XCode 11.3.7 and compiling with Clang C++11. (I haven't messed with the project settings)
Thank you in advance!!!
Use %lld instead of %lli.
The reason %i doesn't work is because 0 is interpreted as a prefix for octal numbers, and the digits 8 and 9 don't exist in octal:
d Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
i Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters
that correspond to the base are used.
You would also get the wrong answer for other numbers, e.g. 010 in octal would be parsed as 8.
Or, even better: use C++ instead of C.
std::cin >> a[i];
When I'm compiling the following source code, in the output the zero doesn't correctly show. Why? I want the output text to have the following format:
01 02 03 04
05 06 07 08
not 1 2 3 4....
How can I fix this issue?
#include "stdio.h"
int main(int argc, char const *argv[])
{
int a[3][4] = {
{00, 01, 02, 03} , /* initializers for row indexed by 0 */
{04, 05, 06, 07} , /* initializers for row indexed by 1 */
{08, 09, 10, 11} /* initializers for row indexed by 2 */
};
for (int i = 0; i < 3; ++i)
{
for (int t = 0; t < 4; ++t)
{
printf("%d\t", a[i][t] );
}
printf("\n");
}
return 0;
}
Check the printf manual page
Look for the padding with 0:
0
The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f,
F, g, and G conversions, the converted value is padded on the left
with zeros rather than blanks. If the 0 and - flags both appear, the 0
flag is ignored. If a precision is given with a numeric conversion (d,
i, o, u, x, and X), the 0 flag is ignored. For other conversions, the
behavior is undefined.
and look for the field width:
The field width
An optional decimal digit string (with nonzero first digit) specifying
a minimum field width. If the converted value has fewer characters
than the field width, it will be padded with spaces on the left (or
right, if the left-adjustment flag has been given). Instead of a
decimal digit string one may write "*" or "*m$" (for some decimal
integer m) to specify that the field width is given in the next
argument, or in the m-th argument, respectively, which must be of type
int. A negative field width is taken as a '-' flag followed by a
positive field width. In no case does a nonexistent or small field
width cause truncation of a field; if the result of a conversion is
wider than the field width, the field is expanded to contain the
conversion result.
solution use:
printf("%02d\b", a[i][t]);
and drop the 0 from literal (01, 02...) or they will be taken as octal numbers.
0 before number tells compiler, that this number is in octal notation. You cannot do this with numbers, only with chars, or with right format in printf. Actually your code is incorrect and should never compiles, since there is no digits 8 and 9 in octal.
I have this very strange problem where if I declare an int like so
int time = 0110;
and then display it to the console the value returned is 72. However when I remove the 0 at the front so that int time = 110; the console then displays 110 like expected.
Two things I'd like to know, first of all why it does this with a preceding 0 at the start of the int and is there a way to stop it so that 0110 at least equals 110?Secondly is there any way to keep it so that 0110 returns 0110?
If you take a crack guess at the variable name I'm trying to do operations with 24hr time, but at this point any time before 1000 is causing problems because of this.
Thanks in advance!
An integer literal that starts from 0 defines an octal integer literal. Now in C++ there are four categories of integer literals
integer-literal:
decimal-literal integer-suffixopt
octal-literal integer-suffixopt
hexadecimal-literal integer-suffixopt
binary-literal integer-suffixopt
And octal-integer literal is defined the following way
octal-literal:
0 octal-literal
opt octal-digit
That is it starts from 0.
Thus this octal integer literal
0110
corresponds to the following decimal number
8^2 + 8^1
that is equal to 72.
You can be sure that 72 in octal representation is equivalent to 110 by running the following simple program
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::oct << 72 << std::endl;
return 0;
}
The output is
110
It is because of Integer Literals. Placing a 0 before number means its a octal number. For binary it is 0b, for hexadecimal it is 0x or 0X. You don't need to write any thing for decimal. See the code bellow.
#include<stdio.h>
int main()
{
int binary = 0b10;
int octal=010;
int decimal = 10;
int hexa = 0x10;
printf("%d %d %d %d\n", octal, decimal, hexa, binary);
}
For more information visit tutorialspoint.
The compiler is interpreting the leading zero as an octal number. The octal value of "110" is 72 in decimal. There's no need for the leading zero if you're just storing an int value.
You're trying to store "time" as it appears on a clock. That's actually more complicated than a simple int. You could store the number of minutes since midnight instead.
Zero at the start means the number is in octal. Without it is decimal.
I am new to C so I do not understand what is happening in this line:
out[counter++] = recurring_count + '0';
What does +'0' mean?
Additionally, can you please help me by writing comments for most of the code? I don't understand it well, so I hope you can help me. Thank you.
#include "stdafx.h"
#include "stdafx.h"
#include<iostream>
void encode(char mass[], char* out, int size)
{
int counter = 0;
int recurring_count = 0;
for (int i = 0; i < size - 1; i++)
{
if (mass[i] != mass[i + 1])
{
recurring_count++;
out[counter++] = mass[i];
out[counter++] = recurring_count + '0';
recurring_count = 0;
}
else
{
recurring_count++;
}
}
}
int main()
{
char data[] = "yyyyyyttttt";
int size = sizeof(data) / sizeof(data[0]);
char * out = new char[size + 1]();
encode(data, out, size);
std::cout << out;
delete[] out;
std::cin.get();
return 0;
}
It adds the character encoding value of '0' to the value in recurring_count. If we assume ASCII encoded characters, that means adding 48.
This is common practice for making a "readable" digit from a integer value in the range 0..9 - in other words, convert a single digit number to an actual digit representation in a character form. And as long as all digits are "in sequence" (only digits between 0 and 9), it works for any encoding, not just ASCII - so a computer using EBCDIC encoding would still have the same effect.
recurring_count + '0' is a simple way of converting the int recurring_count value into an ascii character.
As you can see over on wikipedia the ascii character code of 0 is 48. Adding the value to that takes you to the corresponding character code for that value.
You see, computers may not really know about letters, digits, symbols; like the letter a, or the digit 1, or the symbol ?. All they know is zeroes and ones. True or not. To exist or not.
Here's one bit: 1
Here's another one: 0
These two are only things that a bit can be, existence or absence.
Yet computers can know about, say, 5. How? Well, 5 is 5 only in base 10; in base 4, it would be a 11, and in base 2, it would be 101. You don't have to know about the base 4, but let's examine the base 2 one, to make sure you know about that:
How would you represent 0 if you had only 0s and 1s? 0, right? You probably would also represent the 1 as 1. Then for 2? Well, you'd write 2 if you could, but you can't... So you write 10 instead.
This is exactly analogous to what you do while advancing from 9 to 10 in base 10. You cannot write 10 inside a single digit, so you rather reset the last digit to zero, and increase the next digit by one. Same thing while advancing from 19 to 20, you attempt to increase 9 by one, but you can't, because there is no single digit representation of 10 in base 10, so you rather reset that digit, and increase the next digit.
This is how you represent numbers with just 0s and 1s.
Now that you have numbers, how would you represent letters and symbols and character-digits, like the 4 and 3 inside the silly string L4M3 for example? You could map them; map them so, for example, that the number 1 would from then on represent the character A, and then 2 would represent B.
Of course, it would be a little problematic; because when you do that the number 1 would represent both the number 1 and the character A. This is exactly the reason why if you write...
printf( "%d %c", 65, 65 );
You will have the output "65 A", provided that the environment you're on is using ASCII encoding, because in ASCII 65 has been mapped to represent A when interpreted as a character. A full list can be found over there.
In short
'A' with single quotes around delivers the message that, "Hey, this A over here is to receive whatever the representative integer value of A is", and in most environments it will just be 65. Same for '0', which evaluates to 48 with ASCII encoding.
Could anybody provide a regular expression for a number that has to be between 1 and 17 in length, and could optionally contain a mantissa of up to 4 places? The length of 17 includes both the characteristic and the mantissa.
Edit:
The length of 17 excludes the decimal point.
Valid examples:
12345678901234567
1234567890123.4567
123456789012345.67
12.34
Invalid:
12345678901234.5678 (Length of numerals = 18)
Thanks.
^\d{17}$|^\d{13}(?=.{5}$)\d*\.\d*\d$
Regex explained:
^\d{17}$ //A string of 17 digits
| //or
^\d{13} //13 digits followed by
(?=.{5}$) //5 characters, of which
\d*\.\d* //one is a decimal point and others are digits
\d$ //and the last one is a digit
OK, this is the best I could do:
/^\d{1,17}$|(?=^.{1,18}$)^\d+\.\d{1,4}$/
Basically, match 1-17 digits, or strings of length 1-18 which consist of two sets of digits separated by a period. The right set can only contain between 1-4 digits.
Don't do this completely in regex. The problem becomes nearly trivial in most programming languages, and that way will be easier for you to write, verify, test, and maintain. You can still use regex for part of the solution, of course, but you don't have to. Pseudocode:
m = re.match(r"(?P<before>[0-9]+)(?P<after>\.[0-9]{1,4})?$", input_string)
if not m:
return "no match"
before, after = m.group("before", "after")
after = after[1:] if after else "" # remove period or set to empty string
if len(before) + len(after) > 17:
return "incorrect length"
return "valid"
It's not particularly pretty, but with so few possibilities (0,1,2,3,4 length mantissa) I would probably just list them all:
\d{17}|\d{16}\.\d{1}|\d{15}\.\d{2}|\d{14}\.\d{3}|\d{13}\.\d{4}
in your favourite language, you can do a couple of logical checks, eg Python
num="1234567890133.3456"
if "." in num and len(num)==17 :
n=num.split(".")
if len(n[1])>4:
print "cannot have more than 4 decimal places"
elif len(n)==2 and n[0].isdigit() and n[1].isdigit():
print "yes, decimal"
elif len(num)==17 and num.isdigit():
print "%s is number with no decimal and is exactly 17 digits." % num
else:
print "%s not ok, check length is 17" % num
I have created this regex from above great solutions. may it help any one. Please let me know if you find any bug in it.
String decimalRegex =""+
"^(?!0[\d,])\+?" + // ^ Start of Number
"(\d{0,"+size+"}|" + // Numeric value without group symbol | (OR)
"(\d{0,"+rem(size,groupSize)+"},)?"+
"(\d{0,"+groupSize+"},) {0,"+div(size,groupSize)+"}\d{"+groupSize+"})" + // Numeric value with group symbol
"((([a-zA-Z]{0,2}|\"|\')\s?\+?)|\.)"+
"(\d{0,"+scale+"})?" + // Decimal value without group symbol
"(\s?([a-zA-Z]{0,2}|\"|\'))$"; // Ends with
private int rem(int size,int groupSize ){
int rem = (size - groupSize)%groupSize;
return rem;
}
private int div(int size,int groupSize ){
int div = (size - groupSize)/groupSize;
return div;
}