C - Store Adjacent Digits in Single int Variable | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

28th Aug 2018, 7:13 PM
NULL
NULL - avatar
8 Answers
+ 7
NULL Editied the code, now the output is just like you need https://code.sololearn.com/cqExXxtsX2In/?ref=app
28th Aug 2018, 11:10 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 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
28th Aug 2018, 9:33 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 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]);
28th Aug 2018, 9:12 PM
Babak
Babak - avatar
+ 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.
28th Aug 2018, 9:13 PM
Babak
Babak - avatar
+ 2
nAutAxH AhmAd Wow!!!! It’s perfect!! Thanks a ton!
28th Aug 2018, 11:28 PM
NULL
NULL - avatar
+ 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!
28th Aug 2018, 8:31 PM
NULL
NULL - avatar
+ 1
@C++ Soldier (Babak) Thanks! This works nicely! I’ll play around with it :)
28th Aug 2018, 9:29 PM
NULL
NULL - avatar
+ 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”?
28th Aug 2018, 10:23 PM
NULL
NULL - avatar