Abhishek
Abhishek

Reputation: 33

scanf getting stuck

Im a beginner in C. Im using scanf function in my c program and its getting stuck and the program moves ahead only when i type exit. The part of the code in which Im facing problem is:

while(fread(&emr,recsize_emr,sizeof(emr)/recsize_emr,fp)==1)
{
    if(emr.emr_id==emr_id)
    {
        printf("%s %s %s %d %d %s %s %f \n\n",emr.fname,emr.lname,emr.company_name,emr.emr_id,emr.agt_id,emr.pol_start_date,emr.pol_end_date,emr.amount);
        printf("Enter New First Name, Last Name, Company Name, EmployerID, AgentID, Policy Start Date, Policy End Date, Amount : ");
        scanf("%s %s %s %d %d %s %s %f \n",emr.fname,emr.lname,emr.company_name,&emr.emr_id,&emr.agt_id,emr.pol_start_date,emr.pol_end_date,&emr.amount);
        fseek(fp,-recsize_emr,SEEK_CUR);
        fwrite(&emr,recsize_emr,sizeof(emr)/recsize_emr,fp);
        break;
     }
 }

Upvotes: 2

Views: 1163

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183978

In

scanf("%s %s %s %d %d %s %s %f \n");

the final " \n" consumes all whitespace after the float has been read. That means the scanf only returns after it received a non-whitespace character after the float - for that character to reach the program, you typically need to enter a newline after it.

If you remove the final whitespace from the format string,

scanf("%s %s %s %d %d %s %s %f");

the scanf returns as soon as it finished reading the float. Then it will leave the newline - or whatever character follows the float in the input` in the input buffer, so it is probably necessary to clear the input buffer before further scans.

Upvotes: 2

Related Questions