-4

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.

smriti
  • 1,073
  • 1
  • 13
  • 25
  • 2
    What have you tried so far? What do you already know about c string parsing that might be relevant? There are dozens of ways to solve your issue, but we want to be able to help you understand the solution, not just give you code. – Davy M Oct 18 '17 at 16:28
  • 2
    Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Oct 18 '17 at 16:29
  • I also recommend you get [a good beginners book or two](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) to read. If you already know the basics then concentrate on the chapters about input and output, and pointers and arrays. Besides that, read about the [`strtol`](http://en.cppreference.com/w/c/string/byte/strtol) function. The books and the knowledge of the [`strtol`](http://en.cppreference.com/w/c/string/byte/strtol) function is all you need for this assignment. – Some programmer dude Oct 18 '17 at 16:35
  • Note that the title asks about digits followed by a `!`, but the sample data shows the digits after the exclamation mark. – Jonathan Leffler Oct 18 '17 at 16:40
  • For the exclamation mark first, you can use `sscanf()` effectively. It is marginally harder if the exclamation mark comes second. Are spaces allowed between digits and the mark? – Jonathan Leffler Oct 18 '17 at 16:43
  • Sorry if my question was lame and not up to mark. I figured out the issue I was having. – smriti Oct 18 '17 at 17:29

1 Answers1

1

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.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131