input containing leading zeroes - c++

In c++ will their be any error if we input an integer containing leading zereos.
for eg:
int a;
cin>>a;
we give an input 00 or 01.
or inputing with the help of string for this is a better idea.

Integers (or floats for that matter) do not have leading zeroes. If you want to keep the leading zeroes then you have to read the input as a string instead, and convert it to number when needed. Or you can use formatting to add leading zeroes when printing results.

In c++ will their be any error if we input an integer containing leading zereos.
You might not get what you expect, depending on the settings of the input stream's format flags. The default is to expect user input to always be in decimal. Leading zeros have no effect. What if we turn that off by calling std::cin.unsetf()?
int main () {
int i;
std::cin.unsetf (std::ios::dec);
while (std::cin >> ii) {
std::cout << i << "\n";
}
}
The output will be 25 if you enter 25, but if you enter 025 the output is 21. That's because C++ now interprets a leading zero on input to mean the number that follows is in octal (or in hexadecimal in the case of a leading 0x or leading 0X).

Leading Zeros will be trimmed off. It wont be stored in the memory.

Related

Slicing string character correctly in C++

I'd like to count number 1 in my input, for example,111 (1+1+1) must return 3and
101must return 2 (1+1)
To achieve this,I developed sample code as follows.
#include <iostream>
using namespace std;
int main(){
string S;
cout<<"input number";
cin>>S;
cout<<"S[0]:"<<S[0]<<endl;
cout<<"S[1]:"<<S[1]<<endl;
cout<<"S[2]:"<<S[2]<<endl;
int T = (int) (S[0]+S[1]+S[2]);
cout<<"T:"<<T<<endl;
return 0;
}
But when I execute this code I input 111 for example and my expected return is 3 but it returned 147.
[ec2-user#ip-10-0-1-187 atcoder]$ ./a.out
input number
111
S[0]:1
S[1]:1
S[2]:1
T:147
What is the wrong point of that ? I am totally novice, so that if someone has opinion,please let me know. Thanks
It's because S[0] is a char. You are adding the character values of these digits, rather than the numerical value. In ASCII, numerical digits start at value 48. In other words, each of your 3 values are exactly 48 too big.
So instead of doing 1+1+1, you're doing 49+49+49.
The simplest way to convert from character value to digit is to subtract 48, which is the value of 0.
e.g, S[0] - '0'.
Since your goal is to count the occurrences of a character, it makes no sense to sum the characters together. I recommend this:
std::cout << std::ranges::count(S, '1');
To explain the output that you get, characters are integers whose values represent various symbols (and non-printable control characters). The value that represents the symbol '1' is not 1. '1'+'1'+'1' is not '3'.

Scanf does not read leading 0s if digit after leading 0s are 8 or 9

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];

Why doesn't this function print all the char array as it takes it?

i was trying to convert from a char array to integers and the atoi function is working properly except when i put a zero in the first index...it didn't print it
#include<iostream>
using namespace std;
int main()
{
char arr[]= "0150234";
int num;
num=atoi(arr);
cout << num;
return 0;
}
I expect the output of 0150234 but the actual output is 150234
I think inside the atoi function you have typecasted the string to integer because of which the 0 gets removed. You can never get a 0 printed before a number since it doesn't make sense.
000001 will always be represented as 1.
I hope this clears your doubt.
Binary number representations (such as int) do not store leading 0s because there is an infinite number of them. Rather they store a fixed number of bits which may have some leading 0 bits.
You can still print the leading 0s if necessary:
std::cout << std::setw(4) << std::setfill('0') << 1 << '\n';
Output:
0001
You're confusing two ideas:
Numbers: These are abstract things. They're quantities. Your computer stores the number in a manner that you should not care about (though it's probably binary).
Representations: These are ways we display numbers to humans, like "150234", or "0x24ADA", or "one hundred and fifty thousand, two hundred and thirty four". You pick a representation when you convert to a string. When streaming to std::cout a representation is picked for you by default, but you can choose your own representation using I/O manipulators, as Maxim shows.
The variable num is a number, not a representation of a number. It does not contain the information «display this as "0150234"». That's what arr provides, because it is a string, containing a representation of a number. So, if that leading zero in the original representation is important to you, when you print num, you have to reproduce that representation yourself.
By the way…
Usually, in the programming world, and particularly in C-like source code:
When we see a string like "150234" we assume that it is the decimal (base-10) representation of a number;
When we see a string like "0x24ADA" (with a leading 0x) we assume that it is the hexadecimal (base-16) representation of a number;
When we see a string like "0150234" (with a leading 0) we assume that it is the octal (base-8) representation of a number.
So, if you do add a leading zero, you may confuse your users.
FYI the conventional base-8 representation of your number is "0445332".

WAP to convert octal to binary

In a C++ program to convert octal numbers to binary, I was able to run the program, but the problem is the output is coming,
Enter number in octal: 1
1 in octal:1
But as we know octal is a 3 bit number so what to do to bring the result as 001?
For information, I declared a function, and used a return value of 'binary'(a variable I declared) in the function definition.
Will I declare the binary variable as binary [3]? Or if not, what is the correct way?
#include <iomanip>
cout << setfill('0') << setw(3) << binary
If leading zeros matter to you... this could sort of be a dup. See "How can I pad an int with leading zeros when using cout << operator?" ( How can I pad an int with leading zeros when using cout << operator? ).
Anyway, aside from (in spite of?) the lack of example code in the question... :-)
I would suggest looking at the answer from that post about printf(), which I find to be much more concise than cout formatting.
Try this (assuming your number is stored in a variable named 'i', adjust accordingly):
int i = 0113; // should yield decimal=75, hex=4B, and octal=113.
// important: note that we give printf 3 arguments after the string: i, i, i.
printf("decimal: %06d hex: %06x octal: %06o\n", i, i, i); // zero filled, all 6 long.
printf("decimal: %6d hex: %6x octal: %6o\n", i, i, i); // note lack of leading zeros, still 6 long.
printf("decimal: %d hex: %x octal: %o\n", i, i, i); // just as long as they need to be (1 to many).
This is one place (of many) to get some printf formatting info: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/FUNCTIONS/format.html
fyi - Internally your integers are already in binary, and are already probably using 32 (or maybe 64) bits each... depending on whether they're shot, int, long and so on. So I suspect there isn't much to change your variable declarations.
The trick here is to understand that printf (or cout, if you prefer) generates the characters to represent the binary number (i, above) on your output. This is why the compiler wants you to use 123 for decimal, 0123 for octal (not the leading zero) and 0x123 for hex so it can convert them from characters in your source code (or input at run time) into the proper binary format in a given variable's memory.

Invert 7th bit of hex string C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Change bit of hex number with leading zeros in C++,(C)
I have this number in hex string:
002A05(7th bit is set to 0)
I need to invert 7-th bit of this number, so after conversion I will get
022A05
But in case
ABCDEF(7th bit is set to 1)
I need to get
A9CDEF
But it has to work with every 6 chars hex number.
It need to be 7th bit from left. I'm trying convert OUI to modified EUI64
I tried converting hex string to integer via strtol, but that function strip leading zeros.
Please help me how can I solve it.
Simplest way, but not necessarily the cleanest;
Since only one char is affected, you can just do it using a simple string manipulation; assuming your input is in uppercase in the string input;
input[1] = "23016745AB*******89EFCD"[input[1]-48];
#include <stdio.h>
void flipme(char *buf, const char *inBuf)
{
int x;
sscanf(inBuf, "%x", &x);
x ^= 1 << 17;
sprintf(buf, "%06X", x);
}
int main(void)
{
char buf[16];
flipme(buf, "002A05");
printf("002A05->%s\n", buf);
flipme(buf, "ABCDEF");
printf("ABCDEF->%s\n", buf);
}
Output:
002A05->022A05
ABCDEF->A9CDEF
You wrote:
I tried converting hex string to integer via strtol, but that function strip leading zeros.
The strtol function converts it to a number. It doesn't mean anything to say it strips leading zeroes because numbers don't have leading zeroes -- "6" and "06" are two different ways of writing the same number. If you want leading zeroes when you print it, you can add them then.
num ^ 0x020000
^ is the bitwise xor operator.
Given an integer x, the number with 3rd bit inverted is x ^ 2.
The rest of the answer was given to you earlier.
Note: in the question the bits are counted from highest to lowest, starting at 1. Then 7th bit of a 6 digit hex number is the 3rd bit of its 2nd highest character. Normally bits are counted from lowest to highest, starting from 0 though.