I've created a sudoku game in which you will enter the row number then the column number. I set an if else condition that only numbers 1-9 will be entered. I used getch function instead of cin after entering a number to avoid using the enter button.
But when I enter 1 in row, it won't accept it and it prints the number 49. I've researched about it and learned that getch function is for get character and if you enter 1, it will translate to '1' which is equivalent of 49 in integer. I've found a solution by using getch() -'0' instead of only getch();
It works but I can't seem to understand the explanation about how it works. Can someone explain it how the getch() -'0' works?
Here's where I used the getch() -'0':
cout << "Enter row: "; row = getch() -'0';
if(row > 9 || row < 1) {
cout << "Rows 1 to 9 only!" << endl;
Sleep(1000);
system("cls");
loop -= 1;
} else {
cout << row << "\nEnter column: "; column = getch() -'0';
if(column > 9 || column < 1) {
cout << "Columns 1 to 9 only!" << endl;
Sleep(1000);
system("cls");
loop -= 1;
}
getch() will get the value of a char and translate that to its int value. Which is why you get 49.
Now if chars have int values and 1 is 49, imagine subtracting the int value of 0 away from that. The numbers are in order from 0-9, so if one has 49, then zero has 48. So you are saying, get this int value (1 = 49) and subtract away 0's int value (48), 49-48 = 1.
This works for all char's which represent numbers. Ex: 8 - '0' == 56 - 48 = 8.
This trick is relying on the fact that the encoding for the numbers 0-9 are in order in the character sequence, in ASCII they are the values 48-57. So if the character '4' is typed, it will return 52, and you can convert that to the number via 52 - 48 = 4. The danger of course is that someone will enter a non-number - you need to check carefully for error.
Its similiar as you write
int k=getch() //stores ascii value of the entered character
As the ascii value of character '0' is 48 so if you substract k by 48 u will get the corresponding entered number
similiar thing happens here---
getch()-'0'
getch() returns the ascii code for the pressed key.
The ascii codes for the number 0..9 are contiguous, 0 = 48, 1 = 49, 2 = 50, and so on.
The C/C++ compiler converts a single-quoted character into its ascii code, so '0' compiles to 48.
getch() - '0' is subtracting the ascii code offset of the digits range from the typed number, yielding the offset of the pressed digit from 0. 0 is at offset 0, 1 is at offset 1, 2 is at offset 2, and so on.
Note that you are not subtracting 0 but '0'. This is a big difference because '0' is a char so when you subtract it, you are implicitly converting it to an int value which is 48 in ASCII. So you are basically reading in values that are "indexes" to chars in the ASCII table, then subtracting the index of the first char you care about to get relative "indexes". Your if statement should take care of any invalid chars including letters and symbols so this should work fine.
Related
I'm new in C++ and I have simple problem. I have to change my number (1011) to decimal result. Cmath is included. I try to use pow method but look at my output please:
Code:
char *b = "1011";
int maxPow = 3;
for (int i = 0; i < 3; ++i) {
cout << b[i] * pow(b[i], (maxPow - i) / 1.0) << endl;
}
Output:
5.7648e+006
110592
2401
I try to make it like this:
result = 1*2^3 + 1*2^2 + 0*2^1 + 1*2^0
The problem is with my array? Where? Please, help me if you can.
So, the problem you're running into, is that you are looping over a ascii value and multiplying the ascii value. Try something like int digit = b[i]-'0'; and then substitute where you use b[i] with the variable digit.
subtracting '0' ... means you are subtracting the ascii value of zero from a given character. So subtracting the ascii value of '0' from '0' gives you the numerical value 0, or subtracting ascii '0' from ascii '1', giving you the numerical value 1.
Take a look at - http://www.asciitable.com/index/asciifull.gif to get a better understanding.
Another little demo you can do, is just cout b[i], and you will see the value 48 or 49 printed, as they are the numerical values of ascii 0 and ascii 1, respectively.
I am fairly new to C++ and i have some trouble in understanding character subtraction in c++.
I had this code intially
char x='2';
x-='0';
if(x) cout << "More than Zero" << endl;
This returned More than Zero as output so to know the value of x i tried this code.
char x='2';
x-='0';
if(x) cout << x << endl;
And i am getting null character(or new line) as output.
Any help is appreciated.
According to the C++ Standard (2.3 Character sets)
...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.
So the codes of adjacent digits in any character set differ by 1.
Thus in this code snippet
char x='2';
x-='0';
if(x) cout << x << endl;
the difference between '2' and '0' (the difference between codes that represent these characters; for example in ASCII these codes are 0x32 and 0x30 while in EBCDIC they are 0xF2 and 0xF0 correspondingly) is equal to 2.
You can check this for example the following way
if(x) cout << ( int )x << endl;
or
if(x) cout << static_cast<int>( x ) << endl;
If you just write
if(x) cout << x << endl;
then the operator << tries to output x as a printable character image of the value 2 because x is of type char.
In C/C++ characters are stored as 8-bit integers with ASCII encoding. So when you do x-='0'; you're subtracting the ASCII value of '0' which is 48 from the ASCII value of '2' which is 50. x is then equal to 2 which is a special control character stating STX (start of text), which is not printable.
If you want to perform arithmetic on characters it's better to subtract '0' from every character before any operation and adding '0' to the result. To avoid problems like running over the range of the 8bit value I'd suggest to cast them on ints or longs.
char x = '2';
int tempVal = x - '0';
/*
Some operations are performed here
*/
x = tempValue % 10 + '0';
// % 10 - in case it excedes the range reserved for numbers in ASCII
cout << x << endl;
It's much safer to perform these operations on larger value types, and subtracting the '0' character allows you to perform operations independent on the ASCII encoding like you'd do with casual integers. Then you add '0' to go back to the ASCII encoding, which alows you to print a number.
You are substracting 48 (ascii char '0') to the character 50 (ascii '2')
50 - 48 = 2
if (x) ' true
In C++, characters are all represented by an ASCII code (see http://www.asciitable.com/)
I guess that doing :
'2' - '0'
is like doing
50 - 48 = 2
According to the ASCII table, the ASCII code 2 stands for start of text, which is not displayed by cout.
Hope it helps.
So what your code is doing is the following:
x = '2', which represents 50 as a decimal value in the ASCII table.
then your are basically saying:
x = x - '0', where zero in the ASCII table is represented as 48 in decimal, which equates to x = 50 - 48 = 2.
Note that 2 != '2' . If you look up 2(decimal) in the ASCII table that will give you a STX (start of text). This is what your code is doing. So keep in mind that the subtraction is taking place on the decimal value of the char.
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.
the operator int() function converts the string to an int
class mystring
{
private:
chat str[20];
public:
operator int() // i'm assuming this converts a string to an int
{
int i=0,l,ss=0,k=1;
l = strlen(str)-1;
while(l>=0)
{
ss=ss+(str[l]-48)*k;
l--;
k*=10;
}
return(ss);
}
}
int main()
{
mystring s2("123");
int i=int(s2);
cout << endl << "i= "<<i;
}
So what's the logic behind operator int() ? What's the 48 in there? Can someone explain to me the algorithm behind the conversion from string to int.
Yes this converts a string to an integer. 48 is the ASCII value for '0'. If you subtract 48 from an ASCII digit you'll get the value of the digit (ex: '0' - 48 = 0, '1' - 48 = 1, ..). For each digit, your code calculates the correct power of 10 by using k (ranges between 1...10^{ log of the number represented by the input string}).
It does indeed convert a string to an integer. The routine assumes that all characters are decimal digits (things like minus sign, space, or comma will mess it up).
It starts with the ones place and moves through the string. For each digit, it subtracts off the ASCII value of '0', and multiplies by the current place value.
This does indeed convert the string to an integer. If you look at an ascii table the numbers start at the value 48. Using this logic (and lets say the string "123") the while loop will do:
l=2
ss=0+(51-48)*1
so in this case ss = 3
next loop we get
l=1
ss=3+(50-48)*10
so ss = 23
next loop
l=0
ss=23+(49-48)*100
so ss= 123
The loop breaks and we return an integer of value 123.
Hope this helps!
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.