I have a char array like the following
charArray[0] = '1'
charArray[1] = '2'
charArray[2] = '3'
charArray[3] = '4'
charArray[4] = '5'
How to combined the char value of above array into a int like the following ?
But I don't want to combined all the value in to a int
I only want to combined charArray[0]~charArray[3] into int
int number = 1234;
How to combined the char value of above array into a string ?
I hope, by showing you the following line, this will give you a better idea how to tackle programming problems.
int number = (charArray[0] - '0')*1000 +
(charArray[1] - '0')*100 +
(charArray[2] - '0')*10 +
(charArray[3] - '0');
Cheers.
You should use the atoi function:
int atoi (const char * str);
recives a string and returns it as a value of type int.
and the function stncpy:
char * strncpy ( char * destination, const char * source, size_t num );
Copies the first num characters of source to destination.
Create a new string(with the strncpy function) containing only the 4 first chars of the charArray and then use the function atoi on the result
This way you could take any size of string you want from the charArray, without manually having to calculate the number
Example (based on your code, assuming you want to keep the charArray as is without changing it) :
int main(void)
{
char charArray[6]="12345";
char newcharArray[5];//one char less than charArray
strncpy(newcharArray,charArray,4);
printf("%d\n",atoi(newcharArray));
}
you can also use alternative methods.
Please check: Converting string to integer C
You can also use strtoumax() function.
see the example : http://pic.dhe.ibm.com/infocenter/zos/v1r12/index.jsp?topic=%2Fcom.ibm.zos.r12.bpxbd00%2Fstrtoumax.htm
Related
EXAMPLE:
If I have this string/array: "123 45 6" (The numbers are separated by at least one space), how can I separate the numbers so I can use the numbers 123,45 and 6 separately?
I have know idea how to do it.
Thanks for helping!
Try strtol() (prototype in <stdlib.h>)
char data[] = "123 45 6";
char *p = data;
while (*p) {
long k = strtol(p, &p, 10);
/* add error checking */
printf("%ld\n", k);
}
Though I find the strtol-approach of png the most elegant way, let me also propose an approach utilising the "%n"-feature of scanf. This feature returns the number of characters scanned so far and can be used for pointing to the next portion to read in:
int main() {
const char *data = "123 45 6 ";
while (data && *data) {
int value=0;
int index=0;
if (sscanf(data,"%d%n",&value,&index) != 1)
break;
printf("%d\n", value);
data+=index;
}
}
You have to create a function which will split your string in a double array of strings, using spaces as a delimiter.
The prototype of this function would be for example :
char **StrSplit(char *str, char c);
Then you would be able to call it in your code with str as the string you want to take the numbers from, and c as the space character (or any character used as a delimiter).
It would return a double array of strings containing in each entry a string for each number.
Then you would be able to convert each entry (containing a string of numbers) as an integer using the function atoi on it.
I have tried the standard methods but still I get error in my answer.
My code:
int main() {
int val;
char str[] = {'1', '45', '0'};
val = str[1] - '0';
printf("Int value = %d\n", val);
return(0);
}
I am getting answer as 5 instead of 45.
How do I solve this issue?
[update from comment:]
I actually need to process an array of strings..suppose I want to convert octal numbers to decimal, and my input has to be in the form of an array of strings. I wish to convert these no.s to decimal : {45,17,100} For that I would, at first be requiring to extract each element and change it to integer. Could you plz suggest what would be the best way to do it?
I actually need to process an array of strings
What you have defined here
char str[] = {'1', '45', '0'};
is not an array of strings, but exactly one array of char with 3 elements. It is not even a C-"string", as this would require a trailing value of 0. Note that the value of the character '0' isn't 0, but, for example, for the ASCII character set it's 48.
'45' is a multi-byte character literal, which in fact is an integer. The code above tries to initialise the 2nd element of the char-array str (str[1], which is a char) using this very literal.
This does not work.
A char cannot (necessarily) hold the int value of this multi-byte character literal. In this case the initialisation of str[1] overflows, resulting in the unexpected value of 5.
To see the issue try the following code:
#include <limits.h>
#include <stdio.h>
int main(void)
{
char c_min = CHAR_MIN;
char c_max = CHAR_MAX;
unsigned char uc = '45';
printf("'1'=%d\n", '1');
printf("'45'=%d\n", '45');
printf("'0'=%d\n", '0');
printf("lowest possible value for char=%d\n", c_min);
printf("highest possible value for char=%d\n", c_max);
printf("'45' converted to an (unsigned) char=%u\n", uc);
return 0;
}
The example above shows how the value of 45 gets truncated when being assigned to char.
Depending on the C implementation you use the conversion of '45' to a char might even invoke the infamous Undefined Behaviour. This is not good.
What you seem to be wanting is:
#define ARRAY_SIZE_MAX 3
char * str[ARRAY_SIZE_MAX] = {"1", "45", "0"}; /*. Mind the double quotes. */
This defines an array of 3 pointers to char , with each pointing to a C-"string".
Here, you are getting 5 instead of 45 because st[1] = '5', this is because we have only ASCII value of 0 to 9 integers and 45 have no ASCII value.
To store 45 in your string you have to declare multidimensional string.
for example:
char st[3][3]={'1', '45', '0'};
Here is the working code:
#include<stdio.h>
int main(){
int i,ans,j;
char st[3][3]={{'1'}, {'4','5'},{'0'}};
for(j=0;j<3;j++){
for(i=0;st[j][i]>=48 && st[j][i]<=57;i++){
ans=st[j][i]-'0';
printf("%d",ans);
}
printf("\n");
}
return 0;
}
Output is
1
45
0
It depends, what do you want.
Every character has it's own int value- It's simply ASCII code
If you will iterate over integers and make it print like %c you will get ASCII table (you can see it eg. there.
But if you want to read int values from string / char datatype you will have to parse it- atoi (ascii to integer) function- example there
Btw I dont know how exactly your example works but the problem is you are doing following: int val = '45' - '0'; int value of '0' should be 48, '45' rly I dont know, but '4' is 52int and '5' is 53 int, so something like that..
As i wrote you should to do something like int val = atoi('45') - atoi('0') just for sure maybe better to cast into int as follows int val = (int) (atoi('45') - atoi('0')) - exactly asi in your example
int main() {
int val;
char str[] = {'1', '45', '0'};
val = (int) (atoi(str[1]) - atoi('0'));
printf("Int value = %d\n", val);
return(0);
}
Not sure, but i think that should works, hope that will help
I have parsed some date and time from GPS receiver. And need to convert them from string to int:
char year[4] = "2014";
char month[2] = "01";
char day[2] = "24";
char hour[2] ="12";
char minute[2] = "58";
char second[2] = "39";
GPS_current_year = atoi(year);
GPS_current_month = atoi(month);
GPS_current_day = atoi(day);
GPS_current_hour = atoi(hour);
GPS_current_minute = atoi(minute);
GPS_current_second = atoi(second);
After executing these the results are:
Somehow part of minutes string is converted when converting hour string. Same with minutes and seconds.
The strings are placed side by side in the memory.
If I change the sequence of defining strings then seconds may be added to years etc.
Questions:
What may cause this error?
Is there any way to avoid this error with using atoi?
I know that I can convert using a loop one char at a time. Just trying to find why is it not working.
Besides the missing quotes around the strings your char array's size should be defined to hold one more char the EOS (end of string a binary zero).
Since the memory representation would be e.g. "2014\0"
char year[4+1] = "2014";
Suggest not trying to define the string size as 4 or 5.
Let the compiler determine the string size.
char year[] = "2014";
In this case, the compiler will make year with a size of 5 initialized with '2', '0', '1', '4', '\0'.
OP's defining the size as 4 resulted in a size of 4-char array without a terminating '\0', which not being a string, create problems with atoi(year).
You forgot quotes in the strings:
char year[4] = "2014";
atoi() converts string to integer. But you are giving non string values to your string variables. Change your code to
char year[5] = "2014";
char month[3] = "01";
char day[3] = "24";
char hour[3] ="12";
char minute[3] = "58";
char second[3] = "39";
I have a pointer lpBegin pointing to a string "1234". Now i want this string compare to an uint how can i make this string to unsigned integer without using scanf? I know the string number is 4 characters long.
You will have to use the atoi function. This takes a pointer to a char and returns an int.
const char *str = "1234";
int res = atoi(str); //do something with res
As said by others and something I didn't know, is that atoi is not recommended because it is undefined what happens when a formatting error occurs. So better use strtoul as others have suggested.
Definitely atoi() which is easy to use.
Don't forget to include stdlib.h.
You can use the strtoul() function. strtoul stands for "String to unsigned long":
#include <stdio.h>
#include <stdlib.h>
int main()
{
char lpBegin[] = "1234";
unsigned long val = strtoul(lpBegin, NULL, 10);
printf("The integer is %ul.", val);
return 0;
}
You can find more information here: http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/
You could use strtoul(lpBegin), but this only works with zero-terminated strings.
If you don't want to use stdlib for whatever reason and you're absolutely sure about the target system(s), you could do the number conversion manually.
This one should work on most systems as long as they are using single byte encoding (e.g. Latin, ISO-8859-1, EBCDIC). To make it work with UTF-16, just replace the 'char' with 'wchar_t' (or whatever you need).
unsigned long sum = (lpbegin[0] - '0') * 1000 +
(lpbegin[1] - '0') * 100 +
(lpbegin[2] - '0') * 10 +
(lpbegin[3] - '0');
or for numbers with unknown length:
char* c = lpBegin;
unsigned long sum = 0;
while (*c >= '0' && *c <= '9') {
sum *= 10;
sum += *c - '0';
++c;
}
I think you look for atoi()
http://www.elook.org/programming/c/atoi.html
strtol is better than atoi with better error handling.
You should use the strtoul function, "string to unsigned long". It is found in stdlib.h and has the following prototype:
unsigned long int strtoul (const char * restrict nptr,
char ** restrict endptr,
int base);
nptr is the character string.
endptr is an optional parameter giving the location of where the function stopped reading valid numbers. If you aren't interested of this, pass NULL in this parameter.
base is the number format you expect the string to be in. In other words, 10 for decimal, 16 for hex, 2 for binary and so on.
Example:
#include <stdlib.h>
#include <stdio.h>
int main()
{
const char str[] = "1234random rubbish";
unsigned int i;
const char* endptr;
i = strtoul(str,
(char**)&endptr,
10);
printf("Integer: %u\n", i);
printf("Function stopped when it found: %s\n", endptr);
getchar();
return 0;
}
Regarding atoi().
atoi() internally just calls strtoul with base 10. atoi() is however not recommended, since the C standard does not define what happens when atoi() encounters a format error: atoi() can then possibly crash. It is therefore better practice to always use strtoul() (and the other similar strto... functions).
If you're really certain the string is 4 digits long, and don't want to use any library function (for whatever reason), you can hardcode it:
const char *lpBegin = "1234";
const unsigned int lpInt = 1000 * (lpBegin[0] - '0') +
100 * (lpBegin[1] - '0') +
10 * (lpBegin[2] - '0') +
1 (lpBegin[3] - '0');
Of course, using e.g. strtoul() is vastly superior so if you have the library available, use it.
Given a char, how to convert this char to a two digit char, which is the hex value of the binary presentation?
For example, given a char, it has a binary presentation, which is one byte, for example, 01010100, which is 0x54.....I need the char array of 54.
Actually it would be:
char c = 84;
char result[3];
sprintf(result,"%02x",c);
This is all far to easy readable :-)
#define H(x) '0' + (x) + ((x)>9) * 7
char c = 84;
char result[3] = { H(c>>4), H(c&15) };
The following code, using snprintf() should work:
#include <stdio.h>
#include <string.h>
int main()
{
char myChar = 'A'; // A = 0x41 = 65
char myHex[3];
snprintf(myHex, 2 "%02x", myChar);
// Print the contents of myHex
printf("myHex = %s\n", myHex);
}
snprintf() is a function that works like printf(), except that it fills a char array with maximum N characters. The syntax of snprintf() is:
int snprintf(char *str, size_t size, const char *format, ...)
Where str is the string to "sprint" to, size is the maximum number of characters to write (in our case, 2), and the rest is like the normal printf()