简体   繁体   中英

fgets reading previous line before input

when I enter an input, the question repeats before i can enter a string.

printf("Enter %d coefficients starting from the 0th degree.\nSeparate them by commas: ", degree+1);
fgets(coeffs_string, MAX, stdin);
for(i=0;i<strlen(coeffs_string);i++){
    if(coeffs_string[i]==','){
        commas++;
        continue;
    }
    else if(isdigit(coeffs_string[i]) || coeffs_string[i]==' ')
        continue;
    else{
        printf("\007Error! A character was found during the input!\n");
                coeffs_string[0]='\0';
        commas=0;
        break;
    }
}

also, it prints the error handler even when i enter the proper input. I tried using scanf but it just stops. is there a way for fgets or scanf to not quickly read the input? *edit:sorry:i forgot some parts of my code

  1. Try putting a fflush(stdout); between your printf() and fgets() statements. Alternatively obtain your input on a separate line from your output.
  2. The string returned by fgets() will include the line terminator character/s that the user generated by pushing the enter key. You are not explicitly handling these characters so the error message will always be displayed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM