Search code examples
cstring-parsing

Parse a char string in c to get just the numeric digits after the exclamation mark


If I have something like !23 How can I parse it to get just the number part?

Input: !23 Output: 23

Input: ! Output: Error

Input: !23eds3 Output: Error

This is my approach of getting the numeric digit. But for some reason strcpy is messing up my array where I am storing some data, its deleting the first element in my array.

if (args[0][0] == '!'){ 
  char str_index[1];
  strcpy(str_index, &args[0][1]);
  int index = atoi(str_index);
}

Also I haven't programmed in C a lot this is only my second program in C.


Solution

  • Some hints, but not going to write the code for you:

    Use the string library functions like strchr to find the '!'. Then use strtod to convert a string to a number. Look at strtod's output to see if it had an error or if it was followed by letters.

    Or maybe you want strtol for integers instead.