A
arnuld
Program works fine. Any improvements you can advise ?
/* A simple C program to find the value of a key inside an array. Array
has a unique key then its unique value next to it after
* a colon and space. Every key: value is separated by a newline. We
have to write a program to find and save the value if we
* pass it the key.
*
* VERSION 0.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { SIZE_VALUE = 20 };
char* get_value(const char*, const char*, char*);
int main(void)
{
const char* table = "OS: Linux\n compiler: gcc\n text-editor: Emacs\n
mentor: comp.lang.c\n";
char found_value[SIZE_VALUE] = {0};
const char* key = "arnuld";
printf("Table:\n %s", table);
printf("------------------------------\n\n");
if(get_value(table, key, found_value)) printf("%s = %s\n", key,
found_value);
return 0;
}
char* get_value(const char* t, const char* k, char* f)
{
int f_idx;
char* p = NULL;
size_t len_of_key = strlen(k);
/* printf("len_of_key: %lu\n", (unsigned long) len_of_key); */
p = strstr(t, k);
if(NULL == p)
{
printf("IN: %s: No Match for key\n", __func__);
return p;
}
/* It actually is: p = p + (len_of_key - 1) but we have 1 colon and 1
space before the value, hence + 2 to it */
p += len_of_key + 1;
for(f_idx = 0; *p != '\n'; ++p, ++f_idx)
{
f[f_idx] = *p;
}
/* printf("value: %s\n", f); */
return f;
}
--,
www.lispmachine.wordpress.com
my email is @ the above blog.
/* A simple C program to find the value of a key inside an array. Array
has a unique key then its unique value next to it after
* a colon and space. Every key: value is separated by a newline. We
have to write a program to find and save the value if we
* pass it the key.
*
* VERSION 0.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { SIZE_VALUE = 20 };
char* get_value(const char*, const char*, char*);
int main(void)
{
const char* table = "OS: Linux\n compiler: gcc\n text-editor: Emacs\n
mentor: comp.lang.c\n";
char found_value[SIZE_VALUE] = {0};
const char* key = "arnuld";
printf("Table:\n %s", table);
printf("------------------------------\n\n");
if(get_value(table, key, found_value)) printf("%s = %s\n", key,
found_value);
return 0;
}
char* get_value(const char* t, const char* k, char* f)
{
int f_idx;
char* p = NULL;
size_t len_of_key = strlen(k);
/* printf("len_of_key: %lu\n", (unsigned long) len_of_key); */
p = strstr(t, k);
if(NULL == p)
{
printf("IN: %s: No Match for key\n", __func__);
return p;
}
/* It actually is: p = p + (len_of_key - 1) but we have 1 colon and 1
space before the value, hence + 2 to it */
p += len_of_key + 1;
for(f_idx = 0; *p != '\n'; ++p, ++f_idx)
{
f[f_idx] = *p;
}
/* printf("value: %s\n", f); */
return f;
}
--,
www.lispmachine.wordpress.com
my email is @ the above blog.