Convert a character digit to the corresponding integer in C
As per other replies, this is fine:
char c = '5';
int x = c - '0';
Also, for error checking, you may wish to check isdigit(c) is true first. Note that you cannot completely portably do the same for letters, for example:
char c = 'b';
int x = c - 'a'; // x is now not necessarily 1
The standard guarantees that the char values for the digits '0' to '9' are contiguous, but makes no guarantees for other characters like letters of the alphabet.
Char to int conversion in C
Yes, this is a safe conversion. C requires it to work. This guarantee is in section 5.2.1 paragraph 2 of the latest ISO C standard, a recent draft of which is N1570:
Both the basic source and basic execution character sets shall have the following
members:
[...]
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.
Both ASCII and EBCDIC, and character sets derived from them, satisfy this requirement, which is why the C standard was able to impose it. Note that letters are not contiguous iN EBCDIC, and C doesn't require them to be.
There is no library function to do it for a single char
, you would need to build a string first:
int digit_to_int(char d)
{
char str[2];
str[0] = d;
str[1] = '\0';
return (int) strtol(str, NULL, 10);
}
You could also use the atoi()
function to do the conversion, once you have a string, but strtol()
is better and safer.
As commenters have pointed out though, it is extreme overkill to call a function to do this conversion; your initial approach to subtract '0' is the proper way of doing this. I just wanted to show how the recommended standard approach of converting a number as a string to a "true" number would be used, here.
How to convert char to int, and vice versa?
Are you talking about a single digit character, like '1'
or '9'
? Then you would do something like this:
char c = '5';
int x = c - '0'; // x == 5
Digit encodings are consecutive in all character character coding schemes (ASCII, EBCDIC, etc.), so subtracting the code for '0'
gives you the right value.
Are you talking about converting the character encoding to an integer? Then all you need to do is assign the character value to an int
:
int x = '5'; // x contains the character encoding of '5' - in ASCII, 53
Are you talking about converting a character string, like "12"
or "42"
? Then you would need to use one of the sscanf
, strtol
, or atoi
library functions (or roll your own equivalent). Given
char str[] = "123";
int x;
you would do
sscanf( str, "%d", &x );
or
x = atoi( str );
or
char *chk;
x = (int) strtol( str, &chk, 10 );
if ( !isspace( *chk ) && *chk != 0 )
// str contained a non-numeric character, handle as appropriate
Convert char to int in C and then printf the value as int?
Test too late
if(argc==3){
tests for required argc
, but unfortunately after using argv[1], argv[2]
. Move test before and exit if not as needed. Note: good use of error message to stderr
.
if (argc != 3) {
fprintf(stderr,"Usage: %s <arguments>\n", argv[0]);
return -1; // or return EXIT_FAILURE
}
Incorrect conversion
Code is converting the pointer and not the referenced text.
#include <stdlib.h>
// a = (int)argv[1];
a = atoi(argv[1]);
Robust code would use strtol()
or perhaps roll your own `strtoi()'
Convert from char * to int
This should help
#include <stdlib.h>
inline int to_int(const char *s)
{
return atoi(s);
}
just in case for an example usage
int main( int ac, char *av[] )
{
printf(" to_int(%s) = %d " ,av[1] , to_int(av[1]) );
return 0;
}
How to properly convert char to int in c++?
As others have mentioned, characters are actually represented as numbers which are mapped to a character table. The number-to-character map differs depending on the chosen charset, e.g., for US-ASCII the characters '1'
and '2'
correspond to the numbers 49 and 50 (see here for the full US-ASCII table).
To convert the string representation of a number into a signed integer use std::stoi
(since C++11).
The following snippet will chop up the string into its individual digits and use std::stoi
to convert them into numbers, respectively.
for (std::string::size_type i = 0, n = total_line.size(); i != n; ++i) {
int d = std::stoi(total_line.substr(i, 1));
std::cout << d << std::endl;
}
Using the standard-library function std::stoi
has the advantage of working regardless of character encoding.
How to convert array of char into array of int in C Programming? [duplicate]
You are confusing single characters with character strings. The latter are sequences of characters (arrays) terminated with a nul
(zero value) character, and that is what the atoi
function expects as its input.
To convert a single character digit to its numerical value, you just need to subtract the value of the zero digit ('0'
) from that character's value (the values of the numerical digits are guaranteed by the Standard to be contiguous).
So, rather than:
array[i] = atoi(&parray[i]);
use:
array[i] = parray[i] - '0'; // Will work if (and only if) parray[i] is a digit.
What is happening in your code is that (by chance) there is a zero byte immediately after the end of your 5-character array (but you can not rely on this), so each atoi(&parray[i])
call is passing a character string starting with, respectively, the '7'
, '1'
, '5'
, '4'
and '2'
characters, and ending only after the '2'
. Thus, you are getting values that represent the numbers formed by the concatenation of your individual array digits. But I repeat: you cannot rely on there being a zero-value character after your array!
LOGIC of Converting a char into an int in C
The function atoi
takes a pointer to a character array as the input parameter (const char*
). When you call note[strlen(note) - 1]
this is a single character (char
), in order to make atoi
work you need to provide the pointer. You do that by adding &
as you've done. This then works, because right after that single digit there is a null character \0
that terminates the string - because your original string was null-terminated.
Note however that doing something like this would not be a good idea:
char a = '7';
int b = atoi(&a);
as there is no way to be sure what the next byte in memory is (following the byte that belongs to a
), but the function will try to read it anyway, which can lead to undefined behaviour.
Related Topics
Vector of Structs Initialization
Finding Version of Microsoft C++ Compiler from Command-Line (For Makefiles)
How to Properly Add Include Directories With Cmake
Why Can Templates Only Be Implemented in the Header File
Accessing an Array Out of Bounds Gives No Error, Why
What Is Meant by Resource Acquisition Is Initialization (Raii)
Capture Characters from Standard Input Without Waiting For Enter to Be Pressed
What Are the Main Purposes of Using Std::Forward and Which Problems It Solves
Erasing Elements from a Vector
Why Do Function Pointer Definitions Work With Any Number of Ampersands '&' or Asterisks '*'
Is It Better in C++ to Pass by Value or Pass by Reference-To-Const
Why Are C Character Literals Ints Instead of Chars
Can a Class Member Function Template Be Virtual
Is "Delete This" Allowed in C++
How to Get the Directory That a Program Is Running From
Checking the Neighbour Values of Arrays
How to Read N Bytes from a File and Put Them into a Vector<Uint8_T> Using Iterators