+ 1
C - Store Adjacent Digits in Single int Variable
My code accepts strings of characters and digits. Any characters will be converted to ASCII value, and each digit will be printed. So the input c35a will output: āASCII value of c: 99ā ā3ā ā5ā āASCII value of a: 97ā However, I would like to store all adjacent digits in a single int variable, then print the variable, so the output would be: āASCII value of c: 99ā ā35ā āASCII value of a: 97ā Here is the code: https://code.sololearn.com/c3ml5rK0ckF8/?ref=app
8 Answers
+ 7
NULL Editied the code, now the output is just like you need
https://code.sololearn.com/cqExXxtsX2In/?ref=app
+ 7
Here, my try
commented every thing that I have included you can set it according to your need :)
https://code.sololearn.com/cqExXxtsX2In/?ref=app
+ 2
int* numbers = malloc(inputSize);
const int IN = 1;
const int OUT = 0;
double num = 0.0;
double inc = 0.1;
int count = 1, c = 0, state = OUT;
for (i = 0; i < inputSize; i++) {
if (!isdigit(input[i])) {
letters[i] = input[i];
getASCII(letters[i]);
state = OUT;
}
else {
num += (input[i] - '0') * inc;
printf("\n%f", num); // shows every step
inc *= .1;
count *= 10;
state = IN;
}
if ( (state == OUT && num > 0.0) ||
(i == inputSize-1 && num > 0.0) ) {
numbers[c++] = (int)(num * count);
num = 0.0;
inc = 0.1;
count = 1;
}
}
for (i = 0; i < c; ++i)
printf("\ninteger is %d", numbers[i]);
+ 2
previous one was wrong. This one might not be elegant but does the job anyway and stores each integer group in an element of the container.
+ 2
nAutAxH AhmAd
Wow!!!! Itās perfect!! Thanks a ton!
+ 1
@C++ Soldier (Babak)
Okay, this is definitely a step forward. But how do I then clear the num variable for reuse? When entering āc25g89ā, the num variable continues to store ā25ā along with ā89.ā So I end up with:
ASCII value of c: 99
52
ASCII value of g: 103
9852
Also, why does the num variable store the digits backwards? This part isnāt such an issue, Iām just wondering.
Thanks!
+ 1
@C++ Soldier (Babak)
Thanks! This works nicely! Iāll play around with it :)
+ 1
nAutAxH AhmAd
Great fix! Thanks!
How could I print the sum variable for adjacent digits only, rather than all the digits at the end of the function? For example, for the input āh98j76ā, the program outputs the ASCII values of h and j, then prints ā9876.ā How could I print āASCII of hā, ā98ā, āASCII of jā, ā76ā?