-2

My task is to get long numeric value from part of char[], where I have the index of its begining and ending. I am just learning C, so it is confusing to me which function works the best in my case..

Lets say im making function getNum():

static char words[100000]; //lets say this is string filled  with many num. values and other stuff.  

long getNum(int begin, int end){
 return (long){part of string starting at words[begin] and ending at words[end]}    
}

I would like to know the best method and easiest method to do this. Any other comments are much appreciated too.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
hou
  • 3
  • 2
  • Sorry, I'm not counting the `code` in question as real effort. – Sourav Ghosh May 26 '15 at 12:05
  • Take a look at `atoi`. [LINK](http://www.codingunit.com/c-reference-stdlib-h-function-atoi-convert-a-string-to-an-integer) – LPs May 26 '15 at 12:06
  • @SouravGhosh too minimal for a minute of you time ://? – hou May 26 '15 at 12:07
  • @hou the problem is that you are asking for a complete solution. Try yourself to do something, and then we can correct or suggest something. This is not a free of charge coding service.... – LPs May 26 '15 at 12:09
  • @hou Sorry again, but I see no reason for your sarcasm. Please read [ask] before posting question. Thank you. :-) – Sourav Ghosh May 26 '15 at 12:10
  • 1
    I had several options to chose from. One would be making new char[end-begin], other would be sscanf, another strtol and probably few more that I am not aware of. I wanted to know which would be the most optmal, with the least code. Such suggestion would help me alot for this task. Knowing the best way would help me in future tasks for sure. Thats why im asking for advice – hou May 26 '15 at 12:22
  • 1
    @hou that you shouled have mentioned in the question body itself, not in the comment. Otherwise, it looks like you are _asking_ for a ready-made solutions. – Sourav Ghosh May 26 '15 at 13:21
  • And, just to add, there can be _various_ ways to achieve the same, depeneding on the structure of the actual _string_ `words`. – Sourav Ghosh May 26 '15 at 13:22

2 Answers2

0

We give the algorithm, you write the code. Agree?

OK, so the logic should be

  1. create an array of chars based on the end-start+1 index range.
  2. do a memcpy() from the source to the new array fro the end-start size.
  3. null-terminate the array.
  4. use strtol() to convert the array to numeric value.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

I realized I don't need index of the end of numeric value.

So far following solution seems the easiest:

static char words[100000]; //lets say this is string filled  with many num. values and other stuff.  
static char *endp;

long getNum(int begin){
 return strtol(&words[begin], &endp, 10);    
}

Sourav Ghosh's solution above to include use of ending index

hou
  • 3
  • 2