Converting array of char into array of integers? [duplicate] - c++

How could I change an array of character (string) to an integer number without using any ready function (ex atoi();) for example :-
char a[5]='4534';
I want the number 4534 , How can I get it ?

Without using any existing libraries, you have to:
Convert character to numeric digit.
Combine digits to form a number.
Converting character to digit:
digit = character - '0';
Forming a number:
number = 0;
Loop:
number = number * 10 + digit;
Your function will have to check for '+' and '-' and other non-digits characters.

First of all this statement
char a[5]='4534';
will not compile. I think you mean
char a[5]="4534";
^^ ^^
To convert this string to a number is enough simple.
For example
int number = 0;
for ( const char *p = a; *p >= '0' && *p <= '9'; ++p )
{
number = 10 * number + *p - '0';
}
Or you could skip leading white spaces.
For example
int number = 0;
const char *p = s;
while ( std::isspace( ( unsigned char )*p ) ) ++p;
for ( ; *p >= '0' && *p <= '9'; ++p )
{
number = 10 * number + *p - '0';
}
If the string may contain sign '+' or '-' then you can check at first whether the first character is a sign.

You can go like this
It's working
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char a[5] = "4534";
int converted = 0;
int arraysize = strlen(a);
int i = 0;
for (i = 0; i < arraysize ; i++)
{
converted = converted *10 + a[i] - '0';
}
printf("converted= %d", converted);
return 0;
}

I prefer to use the std::atoi() function to convert string into a number data type. In your example you have an non-zero terminated array "\0", so the function will not work with this code.
Consider to use zero terminated "strings", like:
char *a = "4534";
int mynumber = std::atoi( a ); // mynumber = 4534

Related

how can I convert character to integer number

How could I change an array of character (string) to an integer number without using any ready function (ex atoi();) for example :-
char a[5]='4534';
I want the number 4534 , How can I get it ?
Without using any existing libraries, you have to:
Convert character to numeric digit.
Combine digits to form a number.
Converting character to digit:
digit = character - '0';
Forming a number:
number = 0;
Loop:
number = number * 10 + digit;
Your function will have to check for '+' and '-' and other non-digits characters.
First of all this statement
char a[5]='4534';
will not compile. I think you mean
char a[5]="4534";
^^ ^^
To convert this string to a number is enough simple.
For example
int number = 0;
for ( const char *p = a; *p >= '0' && *p <= '9'; ++p )
{
number = 10 * number + *p - '0';
}
Or you could skip leading white spaces.
For example
int number = 0;
const char *p = s;
while ( std::isspace( ( unsigned char )*p ) ) ++p;
for ( ; *p >= '0' && *p <= '9'; ++p )
{
number = 10 * number + *p - '0';
}
If the string may contain sign '+' or '-' then you can check at first whether the first character is a sign.
You can go like this
It's working
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char a[5] = "4534";
int converted = 0;
int arraysize = strlen(a);
int i = 0;
for (i = 0; i < arraysize ; i++)
{
converted = converted *10 + a[i] - '0';
}
printf("converted= %d", converted);
return 0;
}
I prefer to use the std::atoi() function to convert string into a number data type. In your example you have an non-zero terminated array "\0", so the function will not work with this code.
Consider to use zero terminated "strings", like:
char *a = "4534";
int mynumber = std::atoi( a ); // mynumber = 4534

Reversing alphabet value of individual characters in string by calculating the difference

I'm trying to write a little function that will flip lowercase characters to their symmetric counterparts in the second half of the alphabet - 26 letters = 13/13.
a = z, b = y, c = x...
I've tried the following code but for some reason it works only for the first character.
Say I enter "bamba"; it begins by switching the 'b' to 'y' but then it gets stuck and replaces all the other character to 'y' as well and I get "yyyyy".
I tried playing around with the code a bit and discovered that if I remove dependency by the current character, I can safely increase all the letters by, say, 1 (a = b, b = c...)
symmetric_difference = 1; **commented out** //21 - toCrypt[i];
I looked all over and the closest thing I found was
"Reversing alphabet value of individual characters in string" but it describes a way that seems weird and redundant.
Can anyone tell me what I did wrong please (assuming that I did)?
#include <iostream>
using namespace std;
void crypto(char[]);
int main()
{
char toCrypt[80];
cout << "enter a string:\n";
cin >> toCrypt;
crypto(toCrypt);
cout << "after crypto:\n";
cout << toCrypt;
}
void crypto(char toCrypt[]) // "Folding" encryption.
{
int size = strlen(toCrypt);
int symmetric_difference;
for (int i = 0; i < size; i++)
{
symmetric_difference = 121 - toCrypt[i]; // Calculate the difference the letter has from it's symmetric counterpart.
if (toCrypt[i] >= 97 && toCrypt[i] <= 110) // If the letter is in the lower half on the alphabet,
toCrypt[i] += symmetric_difference; // Increase it by the difference.
else
if (toCrypt[i] >= 111 && toCrypt[i] <= 122) // If it's in the upper half,
toCrypt[i] -= symmetric_difference; // decrease it by the difference.
}
}
You can try this
for (int i = 0; i < size; i++)
{
toCrypt[i] = 'z' - toCrypt[i] + 'a';
}
In your example, bamba, all of the characters go into the first if statement: toCrypt[i] += symmetric_difference;.
toCrypt[i] += symmetric_difference;
-> toCrypt[i] = toCrypt[i] + 121 - toCrypt[i];
-> toCrypt[i] = 121 = 'y'
Try the following function definition if I did not make a typo.
void crypto( char s[] )
{
static const char alpha[] = "abcdefghijklmnopqrstuvwxyz";
const char *last = alpha + sizeof( alpha ) - 1;
while ( char &c = *s++ )
{
if ( const char *first = std::strchr( alpha, c ) ) c = *( last - ( first - alpha ) - 1 );
}
}
Take into account that it is not necessary that low case letters are ordered sequantially. For example if I am not mistaken it is not valid for EBCDIC.
I would like to substitute statement
const char *last = alpha + sizeof( alpha ) - 1;
for
const char *last = alpha + sizeof( alpha ) - sizeof( '\0' );
but the last is not compatible with C.:)

C++ Atoi function gives error [duplicate]

This question already has answers here:
Convert single char to int
(3 answers)
Closed 3 years ago.
I have a string which has 5 characters. I want to convert each single character to int and then multiply them with each other. This is the code :
int main()
{
int x;
string str = "12345";
int a[5];
for(int i = 0; i < 5; i++)
{
a[i] = atoi(str[i]);
}
x = a[0]*a[1]*a[2]*a[3]*a[4];
cout<<x<<endl;
}
It gives this error for the line with atoi :
invalid conversion from 'char' to 'const char*' [-fpermissive]|
How can I fix this? Thanks.
You can use:
a[i] = str[i] - '0';
Does a char to digit conversion by ASCII character positions.
The proper way to do this is std::accumulate instead of rolling your own:
std::accumulate(std::begin(str), std::end(str), 1, [](int total, char c) {
return total * (c - '0'); //could also decide what to do with non-digits
});
Here's a live sample for your viewing pleasure. It's worth noting that the standard guarantees that the digit characters will always be contiguous, so subtracting '0' from any of '0' to '9' will always give you the numerical value.
std::atoi takes a const char*(a null terminated sequence of characters)
Try to change like
a[i]= str[i]-'0';
You are supplying with a single char hence the compiler is complaining
str[i] is char not char *
Use following :-
int x;
std::string str = "12345";
int a[5];
for(int i = 0; i < 5; i++)
{
a[i] = str[i] -'0' ; // simply subtract 48 from char
}
x = a[0]*a[1]*a[2]*a[3]*a[4];
std::cout<<x<<std::endl;
look at this way
string str = "12345";
int value = atoistr.c_str());
// then do calculation an value in a loop
int temp=1;
while(value){
temp *= (value%10);
value/=10;
}

std::string part into integer

I have a std::string: 01001, I want to get each number:
std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
int res = atoi( foo[i] ); // fail
int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}
How to do that?
This is the easiest way I see:
std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
int res = foo[i] - '0';
}
If you know all characters of foo are digits, you can use (int) (foo[i] - '0') which subtracts the ascii value of '0' from the character. This works for all digits because their ascii values are consecutive.
Your first attempt fails because foo[i] is a single char, while atoi() takes a cstring. Your second attempt fails because &foo[i] is a reference to that character.
Each digit can be obtained by simply using subtraction:
int res = foo[i] - '0';
atoi takes a null-terminated string, not an individual character. The subtraction approach works because the ten decimal digits are guaranteed to be consecutive in the character set (obviously, if there is a chance that you'll have nondigit characters in the string, you'll want to do proper error handling).
One simple way, very close to what you have, would be to insert the char into a predefined string, as such:
std::string foo = "01001";
char str[] = {" "};
for (int i=0; i < foo.size(); ++i)
{
str[0] = foo[i];
int res = atoi( str );
}

Convert Hex String to Hex Value

I have a large hex string
abcdef...
and I want to convert it to
0xab 0xcd 0xef
Are there any functions that do that?
Also could you tell me what I means when people ask are those inputs in ASCII or not?
abcdef are represented as a string. Not sure if that is ASCII or not. not sure what they mean. I am very new to programming so help here would be appreciated. I have a huge string that I need to use in my array and converting it into the aforementioned format will help me initialize my array with the hex string.
You can do this using string streams.
#include <iostream>
#include <sstream>
#include <vector>
int main( int , char ** )
{
const char *str = "AFAB2591CFB70E77C7C417D8C389507A5";
const char *p1 = str;
const char *p2 = p1;
std::vector<unsigned short> output;
while( *p2 != NULL ) {
unsigned short byte;
++p2;
if( *p2 != NULL ) {
++p2;
}
std::stringstream sstm( std::string( p1, p2 ) );
sstm.flags( std::ios_base::hex );
sstm >> byte;
output.push_back( byte );
p1 += 2;
}
for( std::vector<unsigned short>::const_iterator it = output.begin(); it != output.end(); ++it ) {
std::cout << std::hex << std::showbase << *it << "\t" << std::dec << std::noshowbase << *it << "\n";
}
std::cout << "Press any key to continue ...";
std::cin.get();
}
Note that if you use unsigned char instead of unsigned short the conversion from stringstream attempts to convert it into an ASCII character and it doesn't work.
Read in each character one by one and convert it to a hex value (which is pretty easy).
You then need to, before reading the next number multiply the value by 16 (or, indeed, shift it left by 4) and read the next digit before adding it to the number you have so far. Keep going until you reach the end of your string.
When someone asks if they inputs are ASCII they are referring to whether your hex string is encoded using ASCII encoding. There are, equally various other encoding methods that range from the obsolete EBCDIC to the far more modern Unicode (which has different encodings which are still all unicode).
Bear in mind that the numbers 0 to 9, a to f and A to F have ASCII (or indeed unicode) values that are after one another in the encoding. So for numbers you can calculate its REAL value by doing "character - '0'". For 0 this will give you 0 and up to 9 it will give you 9 ...
the kit of parts you need in C is
for (..,i+=2)
and
strtoul(..,16)
Approximately the following (I wish I could made it shorter and use some library functions, any ideas?):
The function string_to_vector takes a character string and its length as input. It goes over the string, processing two characters (str[ i ] and str[ i + 1 ]) at a time. (For odd values of n, the last pass process only one character (str[ i ] though.) Each character is converted to numeric value using the hex_char_to_int method. Then it constructs a number by "joining" the two numeric values by shifting and adding. Finally, the constructed numeric value is appended to a vector of numeric values which is returned at the end of the function.
std::vector< unsigned >
string_to_vector( const char * str, size_t n ) {
std::vector< unsigned > result;
for( size_t i = 0; i < n; i += 2 ) {
unsigned number = hex_char_to_int( str[ i ] ); // most signifcnt nibble
if( (i + 1) < n ) {
unsigned lsn = hex_char_to_int( str[ i + 1 ] ); // least signt nibble
number = (number << 4) + lsn;
}
result.push_back( number );
}
return result;
}
The following function converts characters in the range [0-9A-Za-z] to the corresponding unsigned int value.
unsigned
hex_char_to_int( char c ) {
unsigned result = -1;
if( ('0' <= c) && (c <= '9') ) {
result = c - '0';
}
else if( ('A' <= c) && (c <= 'F') ) {
result = 10 + c - 'A';
}
else if( ('a' <= c) && (c <= 'f') ) {
result = 10 + c - 'a';
}
else {
assert( 0 );
}
return result;
}