arnuld said:
I wrote this program (parser ?) to extract two values from a string
separated by a comma. I extract the values without any problem. Error
checking is there with different kinds of input but in comparison to clc
folks my error checking always looks like Calvin and Hobbes plan for
saving themselves form world war 3.
As usual, any advice om improving the program ? (I wonder why the heck
the value of *pname never changes even when pointer pname is going to
next element for each loop)
/* A program that searches for 2 comma separated values inside a string:
name and number. Name can be anything while number can only be
* an integer greater than zero.
[...]
What about something simple like this:
http://codepad.org/soY31mYl
_____________________________________________________________
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#define STRTOL_VALIDATE(mp_number) \
(! ((! (mp_number) \
|| (mp_number) == LONG_MAX \
|| (mp_number) == LONG_MIN) \
&& errno))
struct name_and_number
{
char* name;
int number;
};
struct name_and_number*
name_and_number_parse(
char const* string
){
long int number;
size_t name_size;
struct name_and_number* self;
char const* name = strchr(string, ',');
if (! name) return NULL;
errno = 0;
number = strtol(name + 1, NULL, 10);
if (! STRTOL_VALIDATE(number) || ((int)number) < 1) return NULL;
name_size = name - string;
if (! name_size) return NULL;
if ((self = malloc(sizeof(*self) + name_size + 1)))
{
self->name = (char*)(self + 1);
memcpy(self->name, string, name_size);
self->name[name_size] = '\0';
self->number = (int)number;
}
return self;
}
#define name_and_number_destroy free
void
name_and_number_parse_and_display(
char const* string
){
struct name_and_number* parsed;
if ((parsed = name_and_number_parse(string)))
{
printf("origin: %s\nname: %s\nnumber: %d\n\n",
string, parsed->name, parsed->number);
name_and_number_destroy(parsed);
}
else
{
printf("failed to parse: %s\n\n", string);
}
puts("------------------------------------------");
}
int
main(void)
{
name_and_number_parse_and_display("Arnul@23,1");
name_and_number_parse_and_display("00#$%^&@23,Arnuld");
name_and_number_parse_and_display("Arnuld,");
name_and_number_parse_and_display("Chris Thomasson, 12.65");
name_and_number_parse_and_display("John Doe,-1234");
name_and_number_parse_and_display("Jane Doe");
name_and_number_parse_and_display("");
name_and_number_parse_and_display("1234,34345,6");
name_and_number_parse_and_display("lzkfjclkdsjfaj,asd123");
puts("\n\n\n___________________________________________\n"
"The program has completed; hit <ENTER> to exit...");
getchar();
return 0;
}
_____________________________________________________________
?