How do I convert a char into int in C++? [duplicate] - c++

This question already has answers here:
How would I convert a char array to int? [closed]
(2 answers)
Closed 8 years ago.
I have created an Array of type char.
In that Array, I am accepting integers.
Like 0, 1 or anything for that matter.
The question asks for summation of values stored into the Array. But since I have declared the array as char type, so 0 would be accepted like '0'. SO, How should I convert '0' to 0.
Also, Can characters greater than 10(ten) also be converted into integers ?
The input is a string of integers; like 00012312.
Also is there a better method of inputting these numbers apart from this generic character Array method.
Thanks in advance for your help.

If you have a character array like this
char a[] = "00012312";
then you can find the sum the following way
int sum = 0;
for ( char *p = a; *p; ++p ) sum += *p - '0';
If you need to convert the content of the array to an integer then you can write
int x = ( int )std::strtol( a );
It is the same as
int x = std::atoi( a );

A char containing 0...9 can be converted to an int by subtracting '0'. Study an ASCII chart to understand why.
char c = '7';
int n = c - '0';

Related

Assigning strlen(s) value to an integer is varying the output, WHY? [duplicate]

This question already has answers here:
c++ vector size. why -1 is greater than zero
(3 answers)
Closed 1 year ago.
char s[100];
cin>>s;
int x=strlen(s);
if((x-2)>=9)
cout<<s[0]<<x-2<<s[x-1]<<endl;
else
cout<<s<<endl;
output for inputting 'a' is 'a' BUT
char s[100];
cin>>s;
if((strlen(s)-2)>=9)
cout<<s[0]<<strlen(s)-2<<s[strlen(s)-1]<<endl;
else
cout<<s<<endl;
OUTPUT of this program for same input 'a' is a18446744073709551615a.
Just assigning strlen(s) value to an integer is avoiding the problem to happen. WHY ??
From where is that garbage value of 18446744073709551615a coming from, and if the "if" condition is being compiled in second case then also , why?
When you input a, strlen will return unsigned (size_t) 1. 1 - 2 will not be -1 but wrap around at 0 and give you a very large unsigned integer (18446744073709551615 in your case).
strlen returns size_t - an unsigned type.
According to integral conversion rules, the type of strlen(s)-2 remains unsigned, which overflows for any strlen(s) less than 2, wrapping around and giving a large positive value (264-1 in your example).
When you first assign strlen(s) to an int variable, the value is converted to type int and the result of 1-2 becomes -1. You can achieve the same by casting strlen(s) to int:
if ((static_cast<int>(strlen(s))) - 2) >= 9) ...
Or just move -2 to the other side of the comparison:
if (strlen(s) >= 9 + 2) ...

Understanding how to convert char[0] to int [duplicate]

This question already has answers here:
How does subtracting the character '0' from a char change it into an int?
(4 answers)
Closed 8 years ago.
I was trying to go in a loop and each time convert a character in a string to it's integer value and I don't mean the ASCII value. Tried to use atoi() with no luck but then I stumbled upon this question Convert single char to int and my code worked. The code is as follows:
std::string tmp = "87532621";
for(i=0;i<tmp.length();i++)
{
**int num = tmp[i] - '0';**
//do some processing
}
I fail to understand why the following line of code works. My question is how is it converting the char value to integer type?
int num = tmp[i] - '0';
Each char in your string is an ascii value. The ascii values are just 7 bit numbers.
The numerical values for the character digits lies in a sequence 0123456789 which is very convenient because it makes it possible to write
int zero = '0' - '0'; // 0 (zilch)
int one = '1' - '0'; // one (1)
int nine = '9' - '0'; // 9 (three times three)
And so on.
The actual numerical values are not important for this to work. The fact that the are next to each other in the character set is.
See wikipedia - ascii for the actual numerical values.

C++ Convert Ascii Int To Char To Int

Im able to convert most things without a problem, a google search if needed. I cannot figure this one out, though.
I have a char array like:
char map[40] = {0,0,0,0,0,1,1,0,0,0,1,0,1... etc
I am trying to convert the char to the correct integer, but no matter what I try, I get the ascii value: 48/ 49.
I've tried quite a few different combinations of conversions and casts, but I cannot end up with a 0 or a 1, even as a char.
Can anyone help me out with this?
Thanks.
The ascii range of the characters representing integers is 48 to 57 (for '0' to '9'). You should subtract the base value 48 from the character to get its integer value.
char map[40] = {'0','0','0','0','0','1','1','0','0','0','1','0','1'...};
int integerMap[40];
for ( int i = 0 ;i < 40; i++)
{
integerMap[i] = map[i] - 48 ;
// OR
//integerMap[i] = map[i] - '0';
}
If the char is a literal, e.g. '0' (note the quotes), to convert to an int you'd have to do:
int i = map[0] - '0';
And of course a similar operation across your map array. It would also be prudent to error-check so you know the resulting int is in the range 0-9.
The reason you're getting 48/49 is because, as you noted, direct conversion of a literal like int i = (int)map[0]; gives the ASCII value of the char.

convert int to char without using ASCII [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How can i convert an int below 10 to a char for example :
5 -> '5'
(convert int to char without using ASCII table)
Since digits are always consecutive in a standard character set, you can write:
int number = 5;
int character = number + '0';
/* Here, character == '5' */
See, for instance, C11 standard.
n1570, § 5.2.1 Character sets
The 10 decimal digits: 0 1 2 3 4 5 6 7 8 9
[...]
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.
The same applies in C++.
n3337, § 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.
If it is number 0-9 it is good to use:
int i = 5;
char ch = i + '0';
But probably the best option is to use itoa()
int i = 124;
char buffer[33];
itoa(i, buffer, 10); //10 mean decimal.
Here's an option
char c;
int x;
//...
switch ( x )
{
case 1:
c = '1';
break;
//and so on
}
And another:
std::map<int, char> mapping;
mapping[1] = '1';
//...
char c = mapping[4];
I'm not sure I understand what you mean by "without using ASCII table", but
int i = 5;
char c = i + '0';
will do what you want. The character codes for '0' through '9' are guaranteed to be consecutive and in the proper order.

Converting array of type char into a int variable

Compiling this on Codepad:
#include <iostream>
using namespace std;
void main (void)
{
char ch[2];
int value;
cout<<"Enter two integers between 0-9"<<endl;
cin.getline(ch,2);
//testing with char array
//(...)
//how could I do operations like '*', '+', '-', or '/' to the char arrays
}
Gives:
Line 4: error: '::main' must return 'int'
compilation terminated due to -Wfatal-errors.
For example:
Lets say ch[0]='5' and ch[1]='3'
what do I need to do so I can do ch[0] - ch[1] = 2 and store into an int value
You wouldn't have to do anything at all in particular. int x = ch[0] - ch[1] works quite as you would expect it to.
I guess that the original exercise would ask you to get two different integer of probably more than 1 character each.
However, the solution to your problem: ch[0] - ch[1].
Why it works?
Ascii character '0' is character 48.
Ascii character '9' is character 48 + 9
now....
'4' - '3' = (48 + 4) - (48 + 3) = 4 - 3 = 1.
There are a few different problems with the code you've posted. main needs to have a return type of int.
int main() { /* .. */ }
Your call to cin.getline will only fill a single character in the array you've declared, because the function call will null terminate the array. You need
char array[3];
cin.getline( array, 3 );
After that, if array[0] contains '5' and array[1] contains '3', you can simply do
array[0] - array[1]
to get the integer result 2.
If you need to deal with numbers outside the range [0..9] you'll need to convert them to their numeric representation. This can be done using std::stringtream or atoi.