I have a string "a" with numbers on it (e.g "I have 4 apples") and I'm trying to get the number "4" into an int variable without it giving me the ASCII code, in this case "52"(ASCII 4 is 52).
I have tried int y = (int)a[8]
but it doesn't work.
I have a string "a" with numbers on it (e.g "I have 4 apples") and I'm trying to get the number "4" into an int variable without it giving me the ASCII code, in this case "52"(ASCII 4 is 52).
I have tried int y = (int)a[8]
but it doesn't work.
If the message is supposed to have the exact shape you gave as an example, then you can try the first part of the code below.
The sscanf()
function analyses a string and can match literals as well as values you extract in variables.
edit
A more flexible version is provided too, in order to detect an integer anywhere in the string.
The idea is to extract the words one by one with %s
and skip them thanks to the end position known with %n
, until such a word is considered as an integer.
/**
gcc -std=c99 -o prog_c prog_c.c \
-pedantic -Wall -Wextra -Wconversion \
-Wc++-compat -Wwrite-strings -Wold-style-definition -Wvla \
-g -O0 -UNDEBUG -fsanitize=address,undefined
**/
#include <stdio.h>
int
main(void)
{
// fixed shape for the message
const char *msg="I have 4 apples";
int number=-1;
if(sscanf(msg, "I have %d apples", &number)==1)
{
printf("number=%d\n", number);
}
// more flexible version
const char *msg2="Number 5 appears here";
while(*msg2!='\0')
{
char word[20]="";
int pos=-1;
sscanf(msg2, "%s%n", word, &pos);
int number=-1;
if(sscanf(word, "%d", &number)==1)
{
printf("number=%d\n", number);
break;
}
msg2+=pos; // skip this word
}
return 0;
}
The way that I tend to do this is to subtract '0'
from it.
e.g.
char x = '8';
int y = x - '0';
A char is normally just an int and ASCII for digits is consecutive, so if you can get the offset from '0'
to your digit, you get the value of the digit.