S
svata
Hello to all,
as a result from my previous post I'm busy with splitting code into
functions.
The one problem ( out of many ) I encounter is how to properly
use/code a function which returns either array of characters(string) or
a pointer to this array.
I read some articles, some other posts and come to this solution:
char *read_name(void){
static char item_name[11];
char *p_item_name;
printf("Enter the description: ");
if (fgets(item_name, sizeof(item_name), stdin) != NULL){
/* if the input contains a new line */
if (( p_item_name = strchr(item_name, '\n')) != NULL ){
*p_item_name = '\0'; /* get rid of new line */
}
else {
while(getchar() != '\n'){ /* get rid of the rest in the buffer */
;
}
}
}
return item_name; /* return string in the form of character array */
}
Are there other solutions? What are the pros and cons using
array/pointer?
svata
as a result from my previous post I'm busy with splitting code into
functions.
The one problem ( out of many ) I encounter is how to properly
use/code a function which returns either array of characters(string) or
a pointer to this array.
I read some articles, some other posts and come to this solution:
char *read_name(void){
static char item_name[11];
char *p_item_name;
printf("Enter the description: ");
if (fgets(item_name, sizeof(item_name), stdin) != NULL){
/* if the input contains a new line */
if (( p_item_name = strchr(item_name, '\n')) != NULL ){
*p_item_name = '\0'; /* get rid of new line */
}
else {
while(getchar() != '\n'){ /* get rid of the rest in the buffer */
;
}
}
}
return item_name; /* return string in the form of character array */
}
Are there other solutions? What are the pros and cons using
array/pointer?
svata