This question already has answers here:
C++- Adding or subtracting '0' from a value
(4 answers)
Closed 3 years ago.
class Complex
{
public:
int a,b;
void input(string s)
{
int v1=0;
int i=0;
while(s[i]!='+')
{
v1=v1*10+s[i]-'0'; // <<---------------------------here
i++;
}
while(s[i]==' ' || s[i]=='+'||s[i]=='i')
{
i++;
}
int v2=0;
while(i<s.length())
{
v2=v2*10+s[i]-'0';
i++;
}
a=v1;
b=v2;
}
};
This is a class complex and the function input inputs string and convert it into integers a and b of class complex.
what is the requirement of subtracting '0' in this code
The characters representing the digits, '0' thru '9' have values that are (and must be) sequential. For example, in the ASCII character set the '0' character is encoded with the value 48 (decimal), '1' is 49, '2' is 50 and so on, until '9', which is 57. Other encoding systems may use different actual values for the digits (for example, in EBCDIC, '0' is 240 and '9' is 249), but the C standard requires that they are sequentially congruent. From ยง5.2.1 of the C11 (ISO/IEC 9899:201x) Draft:
In both the source and execution basic character sets, the value of
each character after 0 in the above list of decimal digits shall be
one greater than the value of the previous.
Thus, when you subtract the '0' character from another character that represents a digit, you get the numerical value of that digit (rather than its encoded value).
So, in the code:
int a = '6' - '0';
the value of the a will be 6 (and similarly for other digits).
The reason for not just using a value of (say) 48, rather than writing '0' is that the former would only work on systems that use that particular (i.e. ASCII) character encoding, whereas the latter will work on any compliant system.
"What does '0' means in c++" - The symbol '0' designates a single character (constant) with the value 0, which, when interpreted as an ASCII character (which it will be) has the numerical value 0x30 (or 48 in decimal). So, you are basically just subtracting 48.
I dont quite understand the logic of this function but I hope this will help:
'0' is a character literal for 0 in ASCII. The [] operator of string returns a character. So most likely s[i] - '0' is supposed to get you the digit stored in s[i] as a character. Example: '3' -'0' = 3. Note lack of ' around the 3.
The C and C++ standards require that the characters '0'..'9' be
contiguous and increasing. So to convert one of those characters to
the digit that it represents you subtract '0' and to convert a digit
to the character that represents it you add '0'.
In this case the goal is to convert the character in the integer digit that represent.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I'm new to programming and sometimes see expressions like this
...
for (int i=0; i<str1.length(); i++)
{
int sum = ((str1[i]-'0')+(str2[i]-'0'));
str.push_back(sum%10 + '0');
}
...
So that is '0' here? Is it some kind of converting or something?
It's literally the character zero '0'
The operation str[i] - '0' is used to convert the representation of a digit into its numeric value.
Since the characters from '0' to '9' are following in the ascii table, having respectively, the values 48 to 57, when you perform the operation '3' - '0', the interpreter will use the ascii values, 51 - 48 == 3, so you can convert '3' to 3
ASCII Table
(source of the picture : Wikipedia)
'0' is the character zero. Since characters are sequential, adding a digit to 0 will produce the character representing that digit (once cast back to a char). E.g., (char)(2 + '0') (i.e., the integer two plus the character zero) will produce '2' (i.e., the character two).
Well
str2[i] - '0'
Converts character representation of a digit ('3', '7', '9') into its integer value (3, 7, 9). More accurate (and more wordy) construction is
(int)char.GetNumericValue(str2[i])
What is implied, but not really stated, in the other answers is that int and char can be treated as fairly equivalent in c#. You can do math on chars just like you can on ints, and you can convert back and forth between int and char with ease. The number you get is based on the position in the utf8 character tables for the char.
'0' as a char has an int value of 48, so you could do:
int x = 7;
char c = x+48; //c would be '7' as a char, or 55 as an int
Other examples:
char c = 'a';
c++;
Console.Write(c); //prints 'b', because 'a' + 1 is b
It's quite logical and reasonably helpful sometimes* but the main reason you might see '0' is that it's easier to remember '0' than it is to remember 48 (it's slightly easier to remember the hex version 0x30)
All these give you char 5 from int 5:
char five = 5 + 48;
char five = 5 + 0x30;
char five = 5 + '0';
Which one would you find easiest to remember? :)
*for example, say you wanted to count the chars in an ascii string, you could do:
var counts = new int[256];
foreach(char c in string)
counts[c]++;
You can use the char to index the array just like you can an int. At the end of the operation "hello world" would have put a 1 in index 104 (the h), a 3 in index 108(the l) etc..
Sure these days you might use a Dictionary<char, int> but appreciating that intrinsic char/int equivalence and how it can be used has its merits..
What is '0' means?
In C++, it is a character literal.
The fundamental reason why/how str1[i] - '0' works is through promotion.
In particular when you wrote:
str1[i]-'0'
This means
both str1[i] and '0' will be promoted to an int. And so the result will be an int.
Let's looks at some example for more clarifications:
char c1 = 'E';
char c2 = 'F';
int result = c1 + c2;
Here both c1 and c2 will be promoted to an int. And the result will be an int. In particular, c1 will become(promoted to) 69 and c2 will become(promoted to) 70. And so result will be 69 + 70 which is the integer value 139.
I have an example:
int var = 5;
char ch = (char)var;
char ch2 = var+48;
cout << ch << endl;
cout << ch2 << endl;
I had some other code. (char) returned wrong answer, but +48 didn't. When I changed ONLY (char) to +48, then my code got corrected.
What is the difference between converting int to char by using (char) and +48 (ASCII) in C++?
char ch=(char)var; has the same effect as char ch=var; and assigns the numeric value 5 to ch. You're using ASCII (supported by all modern systems) and ASCII character code 5 represents Enquiry 'ENQ' an old terminal control code. Perhaps some old timer has a clue what it did!
char ch2 = var+48; assigns the numeric value 53 to ch2 which happens to represent the ASCII character for the digit '5'. ASCII 48 is zero (0) and the digits all appear in the ASCII table in order after that. So 48+5 lands on 53 (which represents the character '5').
In C++ char is a integer type. The value is interpreted as representing an ASCII character but it should be thought of as holding a number.
Its numeric range is either [-128,127] or [0,255]. That's because C++ requires sizeof(char)==1 and all modern platforms have 8 bit bytes.
NB: C++ doesn't actually mandate ASCII, but again that will be the case on all modern platforms.
PS: I think its an unfortunate artifact of C (inherited by C++) that sizeof(char)==1 and there isn't a separate fundamental type called byte.
A char is simply the base integral denomination in c++. Output statements, like cout and printf map char integers to the corresponding character mapping. On Windows computers this is typically ASCII.
Note that the 5th in ASCII maps to the Enquiry character which has no printable character, while the 53rd character maps to the printable character 5.
A generally accepted hack to store a number 0-9 in a char is to do: const char ch = var + '0' It's important to note the shortcomings here:
If your code is running on some non-ASCII character mapping then characters 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 may not be laid out in order in which case this wouldn't work
If var is outside the 0 - 9 range this var + '0' will map to something other than a numeric character mapping
A guaranteed way to get the most significant digit of a number independent of 1 or 2 is to use:
const auto ch = to_string(var).front()
Generally char represents a number as int does. Casting an int value to char doesn't provide it's ASCII representation.
The ASCII codes as numbers for digits range from 48 (== '0') to 58 (== '9'). So to get the printable digit you have to add '0' (or 48).
The difference is that casting to char (char) explicitly converts the digit to a char and adding 48 do not.
Its important to note that an int is typically 32 bit and char is typically 8 bit. This means that the number you can store in a char is from -127 to +127(or 0 to 255-(2^8-1) if you use unsigned char) and in an int from โ2,147,483,648 (โ231) to 2,147,483,647 (231 โ 1)(or 0 to 2^32 -1 for unsigned).
Adding 48 to a value is not changing the type to char.
In the following code, I can not understand why the string is converted to int in this way.
Why is it using a sum with 0 ?
string mystring;
vector<int> myint;
mystring[i+1]=myint[i]+'0';
This code converts an int (presumably a digit) to the character that represents it.
Since characters are sequential, and chars can be treated as integers, the character representing a certain digit can, in fact, be described by its distance from '0'. This way, 0 turns turn to the character '0', '5' is the character that is greater than '0' by five, and so on.
This is an efficient, old school and dangerous method to get a char representation of a single digit. '0' will be converted to an int containing its ASCII code (0x30 for '0') and then that is added to myint[i]. If myint[i] is 9 or lower, you can cast myint[i] to a char you will get the resulting digit as text.
Things will not go as expected if you add more than 9 to '0'
You can also get a number from its char representation :
char text = '5';
int digit = text - '0';
The '0' expression isn't string type, it's char type that stores characters of ASCII and also can represent numbers from 0 to 255. So, in arithmetic operations char behaves like integer type.
In C strings a represent as arrays of char: static (char str[N]) or dynamic (char *str = new char[n]). String literals puts into double quotes ("string").
So, '0' is char and "0" is char[1]
I am trying to improve my understanding of C++, pointer arithmetic especially. I use atoi pretty often, but I have rarely given thought as to how it works. Looking up how it is done, I understand it mostly, but there is one thing that I am confused about.
Here is an example of a solution I have found online:
int atoi( char* pStr )
{
int iRetVal = 0;
if ( pStr )
{
while ( *pStr && *pStr <= '9' && *pStr >= '0' )
{
iRetVal = (iRetVal * 10) + (*pStr - '0');
pStr++;
}
}
return iRetVal;
}
I think the main reason I have had a hard time grasping how atoi as been done in the past is the way characters are compared. The "while" statement is saying while the character exists, and the character is less-than-or-equal-to 9, and it is greater-than-or-equal-to 0 then do stuff. This statement says two things to me:
Characters can be compared to other characters logically (but what is the returned value?).
Before I looked into this I suppose I knew it subconsciously but I never actually thought about it, but a '5' character is "smaller" than a '6' character in the same way that 5 is less than 6, so you can compare the characters as integers, essentially (for this intent).
Somehow while (*sPtr) and *SPtr != 0 are different. This seems obvious to me, but I find that I cannot put it into words, which means I know this is true but I do not understand why.
Edit: I have no idea what the *pStr - '0' part would do.
Any help making sense of these observations would be very... helpful! Thanks!
while the character exists
No, not really. It says "while character is not 0 (or '\0'). Basically, ASCII character '\0' indicates an end of a "C" string. Since you don't want to go past the end of a character array (and the exact length is not known), every character is tested for '\0'.
Characters can be compared to other characters logically
That's right. Character is nothing but a number, well, at least in ASCII encoding. In ASCII, for instance, '0' corresponds to a decimal value of 48, '1' is 49, 'Z' is 90 (you can take a look at ASCII Table here). So yeah, you can compare characters just like you compare integers.
Somehow while (*sPtr) and *sPtr != 0 are different.
Not different at all. A decimal 0 is a special ASCII symbol (nul) that is used to indicate the end of "C" string, as I mentioned in the beginning. You cannot see or print (nul), but it's there.
The *pStr - '0' converts the character to its numeric value '1' - '0' = 1
The while loop checks if we are not at the end of the string and that we have a valid digit.
A character in C is represented simply as an ASCII value. Since all the digits are consecutive in ASCII (i.e. 0x30 == '0' and 0x39 == '9' with all the other digits in between), you can determine if a character is a digit by simply doing a range check, and you can get the digit's value by subtracting '0'.
Note that posted implementation of atoi is not complete. Real atoi can process negative values.
Somehow while (*sPtr) and *sPtr != 0 are different.
These two expressions are the same. When used as condition, *sPtr is considered true when value stored at address sPtr is not zero, and *sPtr != 0 is true when value stored at address sPtr is not zero. Difference is when used somewhere else, then second expression evaluates to true or false, but the first one evaluates to stored value.
C-style strings are null-terminated.
Therefore:
while ( *pStr && *pStr <= '9' && *pStr >= '0' )
This tests:
*pStr that we have not yet reached the end of the string and is equivalent to writing *pStr != 0 (note without the single quote, ASCII value 0, or NUL).
*pStr >= '0' && *pStr <= '9' (perhaps more logically) that the character at *pStr is in the range '0' (ASCII value 48) to '9' (ASCII value 57), that is a digit.
The representation of '0' in memory os 0x30 and the representation of '9' is 0x39. This is what the computer sees, and when it compares them with logical operators, it uses these values. The nul-termination character is represented as 0x00, (aka zero). The key here is that chars are just like any other int to the machine.
Therefore, the while statement is saying:
While the char we are examining is valid (aka NOT zero and therefore NOT a nul-terminator), and its value (as the machine sees it) is less than 0x39 and its value is greater than 0x30, proceed.
The body of the while loop then calculates the appropriate value to add to the accumulator based on the integer's position in the string. It then increments the pointer and goes again. Once it's done, it returns the accumulated value.
This chunk of code is using ascii values to accumulate an integer tally of it's alpha equivalent.
In regards to your first numbered bullet, it seems quite trivial that when comparing anything the result is boolean. Although I feel like you were trying to ask if the compiler actually understands "characters". To my understanding though this comparison is done using the ascii values of the characters. i.e. a < b is interpreted as ( 97 < 98).
(Note that it is also easy to see that ascii values are used when you compare 'a' and 'A', as 'A' is less than 'a')
Concerning your second bullet, it seems that the while loop is checking that there is in fact an assigned value that is not NULL (ascii value of 0). The and operator produces FALSE as soon as a false statement is encountered, so that you don't do comparison on a NULL char. As for the rest of the while loop, it is doing ascii comparison as I mentioned about bullet 1. It is just checking whether or not the given character corresponds to an ascii value that is related to a number. i.e. between '0' and '9' (or ascii: between 48 and 57)
LASTLY
the (*ptr-'0') is the most interesting part in my opinion. This statement returns an integer between 0 and 9 inclusive. If you take a look at an ascii chart you will notice the numbers 0 through 9 are beside each other. So imagine '3'-'0' which is 51 - 48 and produces 3! :D So in simpler terms, it is doing ascii subtraction and returning the corresponding integer value. :D
Cheers, and I hope this explains a bit
Let's break it down:
if ( pStr )
If you pass atoi a null pointer, pStr will be 0x00 - and this will be false. Otherwise, we have something to parse.
while ( *pStr && *pStr <= '9' && *pStr >= '0' )
Ok, there's a bunch of things going on here. *pStr means we check if the value pStr is pointing to is 0x00 or not. If you look at an ASCII table, the ASCII for 0x00 is 'null' and in C/C++ the convention is that strings are null terminated (as opposed to Pascal and Java style strings, which tell you their length then have that many characters). So, when *pStr evaluates to false, our string has come to an end and we should stop.
*pStr <= '9' && *pStr >= '0' works because the values for the ASCII characters '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' are all contiguous - '0' is 0x30 and '9' is 0x39, for example. So, if pStr's pointed to value is outside this range, then we're not parsing an integer and we should stop.
iRetVal = (iRetVal * 10) + (*pStr - '0');
Because of the properties of ASCII numerals being contiguous in memory, it so happens that if we know we have a numeral, *pStr - '0' evaluates to its numerical value - 0 for '0' (0x30 - 0x30), 1 for '1' (0x31 - 0x30)... 9 for '9'. So we shift our number up and slide in the new place.
pStr++;
By adding one to the pointer, the pointer points to the next address in memory - the next character in the string we are converting to an integer.
Note that this function will screw up if the string is not null terminated, it has any non numerals (such as '-') or if it is non-ASCII in any way. It's not magic, it just relies on these things being true.
Is the code below converting a character into its ASCII value?.
I faced a piece of code while studying evaluation of postfix operation,where it says "the expression converts a single digit character in C to its numerical value".?
int x=getch();
int c=x-'0'; /*does c have the ASCII value of x?*/
printf("%d",c);
No, it's converting the ASCII value to a number >= 0.
Let's say you type '1'. getch() will return 49 which is the ASCII value of '1'. 49 - '0' is the same as 49 - 48 (48 being the ASCII value for '0'). Which gives you 1.
Note that this code is broken if you enter a character that is not a number.
E.g. if you type 'r' it will print 'r' - '0' = 114 - 48 = 66
(Ref.)
No, it's giving the numeric value of a digit. So '5' (53 in ASCII) becomes 5.
Is the code below converting a character into its ASCII value?
It isn't. It's doing the opposite (converting an ASCII value to the numerical value) and it only works for decimal digits.
To print the ascii value all you need to do is :
int x=getch();
printf("%d",x);
If you are sure that you only want to accept integers as input then you need to put some constraints to the input before proceeding to process them.
int x = getch();
if (x >='0' || x <= '9') {
int c = x - '0'; // c will have the value of the digit in the range 0-9
. . .
}
Any character(in your case numbers) enclosed within single quotes is compiled to its ASCII value. The following line in the snippet above translates to,
int c=x-'0'; ---> int c= x-48; //48 is the ASCII value of '0'
When the user inputs any character to your program, it gets translated to integer as follow,
If x = '1', ASCII of '1' = 49, so c= 49-48 = 1
If x = '9', ASCII of '9' = 57, so c= 57-48 = 9 and so on.