In my program doesn't use scanf , I replaced it with fgets,but i've some problems. My scope: have a function that return a char* to a "string",but if is "\n" or " " (space) in the first character it will print an error,and repeat the input.
I wrote this:
#define DIM_INPUT 20
char buffer[DIM_INPUT];
char* readFromInput(){
size_t length = 0;
int cycle = 1;
if(length < 3){
while(cycle){
fgets(buffer,DIM_INPUT,stdin);
length = strlen(buffer);
char first = buffer[0];
char* c = &first;
if(strcmp(c,"\n") == 0){
printf("Error,repeat\n");
cycle = 1;
}
else if(strcmp(c," ") == 0){
printf("Error,repeat\n");
cycle = 1;
}
else
return c;
}
}
else{
if(buffer[length-1] == '\n'){
buffer[length-1] = 0;
}
char* input = malloc(sizeof(char)*length);
strcpy(input,buffer);
if(strlen(buffer)==DIM_INPUT-1) //
CLEAN_STDIN;
memset(buffer,'\0',sizeof(buffer));
return input;
}
}
And CLEAN_STDIN is a macro to consume additional characters:
{ int ch;while((ch = fgetc(stdin))!='\n' && ch != EOF );}
The problem is when using it has some strange problems , especially when I enter in input one character. Thanks