+ 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 Respostas
+ 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â?