I would like to copy the contents of a char array to int variables or an array. For example, the first five values have to go to an int array (int x):
char a[] = "123456";
I saw in other threads that to change a char to an int, I need to do this:
int x = a[0] - '0';
Is there other ways of doing it?
What if I wanted to the values in groups of two or more, such as 12, 34 and 56?
And what if I didn't what to save them as ints, but floats or other types instead?
Copy properly sized portions of the string to a separate buffer and use strtol() or strtod().
You are on write track, however if you want to convert into integer array then you
should use something like
int x[MAX_ELEM];
for(int i =0; i<sizeof(a)/sizeof(char); i++)
{
x[i] = a[i] -'0';
}
For other cases you will need to deal separately.
The reason you have to do int x = a[0] - '0'; is because of the character encoding in C. What is happening is you are subtracting the encoding offset from the character. Here is a table with all the encoding values: UTF-8 encodings. So int x = a[0] - '0'; is equivalent in your case to int x = 49 - 48; which has the correct value you were looking for. By using '0' instead of 0 you are using the char value of 0.
There are other ways of doing it, but this way works well. To use other types, just do type casting after you create the int.
John's way of getting two digit numbers works well. Reposted here, it was number = 10 * digit1 + digit2.
To answer your questions:
Sure, there are other ways of doing it. The way you've shown converts the ASCII value to the digit it represents, but there are other ways.
Read in the number of characters you want, convert each character to a digit, and construct the integer from those digits like number = 10 * digit1 + digit2.
Do type casting after you construct the integers.
Related
I came from python and it was easy to get the middle digit of an integer, for example, from 897 I want the 9:
>>> num = 897
>>> num2 = int(str(num)[1])
>>> num2
9
But how i can do this on C? It's so difficult to convert into string...
Getting a single digit as an int can be done mathematically:
int num = 897;
int dig1 = (num / 1 ) % 10;
int dig2 = (num / 10 ) % 10;
int dig3 = (num / 100 ) % 10;
Division by one on the first line is only for illustration of the concept: you divide by n-th power of ten, starting with 100 = 1.
You can try the modulus operator (%).
In your case
num = 897
lastDigit = num%10; // Which returns 7
lastDigit/= 10;
secondLastDigit = lastDigit%10; //Which returns 9
Do this using a while loop for as long as you want. EG.
while(num>0)
{
digit = num%10;
num/=10;
}
The closest approximation in C to the given Python fragment, and its str operator, is sprintf/snprintf:
int num = 897;
char numstr[30];
sprintf(numstr, "%d", num);
char num2 = numstr[1];
int num2n = num2 - '0';
printf("%d\n", num2n);
To guard against buffer overflow, it's safer to get in the habit of using snprintf rather than sprintf:
snprintf(numstr, sizeof(numstr), "%d", num);
Instead of sprintf and %d, some systems provide an itoa() function (the opposite of atoi) for converting integers to strings, but it's not standard. For more information about converting numbers to strings, see Converting int to string in C.
This is "harder" in C than it is in Python for a couple of reasons. Constructing strings from numbers typically involves calls to snprintf, which is both more flexible and more of a nuisance than just calling str(). You typically have to worry about how big the destination array (here numstr) needs to be; this difficulty stems from C's lack of a first-class string type. And C has no convenience method for converting back and forth between digit characters and their values, so C programmers get used to adding and subtracting the constant '0' (or, if they like to make more work for themselves, 48).
(And the other part of the difficulty stems, I guess, from practicality. C was originally designed for writing operating systems and text editors and system utilities and things. How often do you need the middle digit of a number, anyway?)
I am a novice programmer trying to understand arrays in C. Specifically I want to take the numeric value of a variable and feed it into an array. I tried to assign the value to the array, but failed with error messages. Can someone explain, simplistically, how to push a value into an array and then be able to just access the last digit?
My last attempt:
#include <stdio.h>
unsigned int TMR0 = 158;
int main(void)
{
unsigned int V = TMR0;
unsigned int Random[2] = {V};
printf("%d \n" , *(Random+2));
return 0;
Thanks.
unsigned int Random[2];
Array will be declared with two positions.
Random[0] Random[1] // two accessible positions in that array.
When you are assigning the value to the array,
unsigned int Random[2] = { V} ;
Value will be stored in the first position of array. Random[0].
*(Random+2) will access the position Random[2]. Which is not accessible position for this array. It will lead to undefined behaviour.
Another thing is if you need to assign the values to both the position you have to do like this.
unsigned int Random[2] = {V,V} ;
To access the last element in your array,
*(Random+1) or Random[1]
May this link will help.
You don't actually need an array to access digits of your number -- you just need math.
It's important to realise that "digit" implies a particular numeric base. In the computer, numbers are represented in binary. For convenience, they can be represented in our code using common bases: decimal, hexadecimal, and octal are the ones we generally use in languages like C.
So, to get the last digit in base 10, you would take the value modulo 10:
int val = 158;
int last_digit = val % 10;
printf( "%d\n", last_digit );
If you need to find digits other than the last, you can first perform integer division and then modulo:
int second_to_last_digit = (val / 10U) % 10;
Alternatively you can convert the number into a string, and then look at each character in that string. But I'm not going to go into that here, since it can be confusing to provide too much information to new programmers.
I am trying to take two elements of an array of integers, and append them, in order, into another array element, but only one.
Eg. int i[14] has all elements filled with numbers.
I want i[1] and i[2] stored into one element: temp[0].
Say i[1] = 123 and i[2] = 456, I want temp[0] = 123456.
I tried using strcat(), but it only works for type char.
Any suggestions?
Edit - I am working in C, not C++. Sorry.
No need to use string functions for this, you can do it with math, which is more efficient anyway:
temp[0] = pow(10, int(log10(i[2]))) * i[1] + i[2]
The idea is to figure out how many decimal places are in i[2] (3 if i[2] is 456), make 10 to that power to get 1000 which is the multiplication factor to then apply to i[1], so it comes out like this:
1000 * 123 + 456 == 123456
In your example: temp[0] = i[1] * 1000 + i[2];
In general you may want to work with any length of i[2]. So you will need to multiply by the right power of 10.
Here's one way to go about it:
int output = i[1];
for ( int x = i[2]; x; x /= 10 )
output *= 10;
output += i[2];
When doing this, bear in mind that an int can only hold values up to INT_MAX (typically 2147483647). If you overflow this then the behaviour is undefined. Consider using unsigned long long instead, and adding in overflow checks.
C : convert to integer using bits
I need to get integer value from bit arrays of 0, 1.
I want to pass integer arrays and get the decimal number using bit operator.
The following is what I tried but does not work when I tried to pass int arrays, it works with char* array. Is there any way that I can pass int arrays and convert it to decimal number? I want to use bit operator.
int toInt(int* bin_arr) {
int val = 0;
while (*bin_arr)
val = (val << 1) | (*bin_arr++ == '1');
return val;
}
Thanks in advance.
Your loop condition assumes that the array is 0-terminated, which is valid for strings, but not integer arrays. One way to fix this would be to pass a length parameter along with the int pointer, so you know when to stop iterating.
Also, in this expression:
(*bin_arr++ == '1')
you should remove the single quotes, if you're passing integers rather than characters.
I got a set of characters as input using scanf which is actually like this "1854?156X".
(using scanf("%c",&input[i]) , input is an array of 10 characters);
In further processing of code I want to multiply the (first digit *10) & (second digit *9) and so on.
So, while multiplying it is taking the ASCII value of 1 which is actually (49 *10), instead of (1*10).
input[i]*counter;
where counter is
int counter=10;
How can I convert the char array to integer array where the exact digit should be multiplied instead of ascii value of that character?
If you know ahead of time that you value is ascii then simply subtract the value of '0' from it. E.g. '9' - '0' = 9'
Definitely use atoi(). It spares you a lot of manual character checking.
int input_val = atoi(input);
int temp = input_val;
while(temp)
{
int digit = temp % 10;
temp /= 10;
}
This gives you each digit from right to left in "digit". You can construct your number using addition and multiplying by powers of 10.
Take the ascii value and subtract 48.
That is input[i] - '0'
...or rather use atoi(). It returns zero if it fails on conversion, so you don't need to bother with '?' and such characters in your array while you traverse it.
Use strtol to convert these character strings into integral types.
It's superior to atoi because the failure modes are not ambiguous.