-Eliminate the undefined behavior.
done.
-Delete the useless cast.
Will see it later. Right now focusing on 1 part of program only, See the
code down.
-Eliminate the wasted vertical space. -Don't use tabs for indenting.
-Indent consistently.
I don't get it. I use Emacs and using tab whatever default indenting is
there I use it. Normal indentation is 2 space when I press tab for
writing function definition and from there indentation increases at the
rate of 2 spaces per indentation. I think 2 spaces are fine. You have
some other/better way ?
-Align your braces. Some of your } are under the corresponding {;
others are not.
-Delete unused enum values.
done. See if this is fine, only then we will go to next "char to int"
function commented here.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
enum
{
VAL_ERR = -1,
VAL_TRUE = 1,
SIZE_VALUE = 10,
ERR_CONVERSION_CHAR_TO_INT = -10
};
/* int get_int_value_using_char_key(const char* t, const char* k); */
void get_value_using_key(const char* t, const char* k, char* f);
int main(void)
{
int v_int = VAL_ERR;
char v_str[SIZE_VALUE+1] = {0};
/* const char* desc = "This is the value of Content: 123\n and this is
Size: 98"; */
const char* desc = "Size of elephant: huge\nSize of ant: tiny";
char* k1 = "ant";
char* k2 = "Size";
get_value_using_key(desc, k1, v_str);
printf("v_str = \"%s\"\n", v_str);
/*
v_int = get_int_value_using_char_key(desc, k2);
printf("v_int = %d\n", v_int);
*/
return 0;
}
/* returns the integer value corresponding to the key mentioned as const
char* k
int get_int_value_using_char_key(const char* t, const char* k)
{
int v = 0;
char value_str[SIZE_VALUE+1] = {0};
get_value_using_key(t, k, value_str);
if(value_str[0])
{
v = strtol(value_str, (char**) NULL, 10);
if(0 == v && ERANGE == errno) return ERR_CONVERSION_CHAR_TO_INT;
}
return v;
}
*/
void get_value_using_key(const char* t, const char* k, char* fill_value)
{
int f_idx;
const int fill_size = SIZE_VALUE; /* can not use strlen(f) here as
fill_value is full of null characters */
char* p = NULL;
size_t len_of_key = strlen(k);
while(VAL_TRUE)
{
p = strstr(t, k);
if(NULL == p) return;
if(*(p-1) == ' ')
{
p += len_of_key;
if( *p == ':' && *(p+1) == ' ' )
{
p += 2; /* Removing the colon and next space after colon */
for(f_idx = 0; (f_idx != fill_size) && (*p != '\n'); ++p, +
+f_idx)
{
fill_value[f_idx] = *p;
}
break;
}
}
else
{
t = p + len_of_key;
}
}
}
======================= OUTPUT =====================
[arnuld@dune programs]$ gcc -ansi -pedantic -Wall -Wextra get-value-from-
key.c
get-value-from-key.c: In function ‘main’:
get-value-from-key.c:28: warning: unused variable ‘k2’
get-value-from-key.c:22: warning: unused variable ‘v_int’
[arnuld@dune programs]$ ./a.out
v_str = "tiny"
[arnuld@dune programs]$