ok, first read the line in with fgets.
Code:
#include <string.h> //for strlen()
char line[1024];
fgets(line, sizeof(line), stdin);
line[strlen(line) - 1] = '\0'; //removes the '\n'
if the number is always going to be found at
the end of the string, then you can pass
strtol() the address of the number located
within the string, like this:
Code:
#include <stdlib.h> //for strtol()
char *endp;
num = strtol(&line[strlen(line) - 1], &endp, 10);
heres the prototype for strtol():
long strtol(char *string, char **endp, int base);
strtol will attempt to convert the string to whatever
base you specified and return it as a long int. endp
will point to '\0' if the entire string was converted
successfully. if it fails, strtol will return as much of
the string it could convert and endp will point to the
first character it couldnt. thats why &line[stren(line) - 1]
was used instead of just line. by doing that we made sure
that strtol didnt encounter any of the characters before
the digit.
if the number isnt always the last character in the string,
simply pass strtol &line[strcspn(line, "1234567890")]
instead of &line[strlen(line) - 1].
strcspn returns the number of characters skipped until
it reached one of the characters in the character set.
that number is used as an index for line.
make sure you include <string.h>.
also, you can just use sscanf() like the first guy said.
Code:
sscanf(line,"%*[^1234567890] %d", &num);
the "%*[^1234567890]" portion basically says skip over
any non-digit characters.
finally, if you have more than one number within the string,
you can loop through the string and store all digits in an
array of int.
Code:
#include <ctype.h> //for isdigit()
for(i = 0, j = 0; i < strlen(line); ++i)
{
if(isdigit(line[i]))
{
iArray[j++] = strtol(&line[i], &endp, 10);
while(isdigit(line[i])) ++i;
}
}
i suggest you use whatever resources you have to look
up the string.h functions.
hope this helps.