-2

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

ameyCU
  • 16,489
  • 2
  • 26
  • 41
minimanimo
  • 35
  • 1
  • 2
  • 9
  • Possible duplicate of [fgets instructions gets skipped.Why?](http://stackoverflow.com/questions/2907062/fgets-instructions-gets-skipped-why) – gsamaras Oct 12 '15 at 14:17
  • 2
    DO NOT do `strcmp(c,"\n")`, which should be undefined behavior. You should compare them in straight way: `c == '\n'`. Also don't do `strcmp(c," ")`, either. – MikeCAT Oct 12 '15 at 14:17
  • 1
    returning `c` in this codemakes no sense because `c` points `first`, which is non-static local variable and will vanish on returning. – MikeCAT Oct 12 '15 at 14:19
  • To begin with, what is "string" here? – MikeCAT Oct 12 '15 at 14:20

1 Answers1

1
if(strcmp(c,"\n") == 0){

Undefined behaviour. Try:

if(c == '\n'){

Similarly for the second instance of it.

Magisch
  • 7,312
  • 9
  • 36
  • 52
  • warning: comparison between pointer and integer [enabled by default] else if(c == ' '){ for your solution,I must replace c with first,beacuse "first" is the first char of buffer. c is char* of it. – minimanimo Oct 12 '15 at 14:49
  • @minimanimo Either substitute `c` with `first` or add an asterisk before `c`. – Spikatrix Oct 12 '15 at 15:26