Could not find an error in this C program

I can not find the error in this program C.

#include <stdio.h>

int main()
{ 

    struct book 
    { 
        char name ; 
        float price ; 
        int pages ; 
    } ;

    struct book b[3] ;
    int i ; int k;
    for ( i = 0 ; i <= 2 ; i++ )
    { 
        printf ( "\nEnter name, price and pages: " ) ;
        k = scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
    } 
    for ( i = 0 ; i <= 2 ; i++ ) 
        printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;
    //getch();
    return 0;
}

lead time:

Enter name, price and pages: a 1 1

Enter name, price and pages: b 2 2

Enter name, price and pages:
a 1.000000 1

 7922540190797673100000000000000000.000000 4200368
b 2.000000 2

I wanted to give a 1 1, b 2 2, c 3 3as my inputs for each scanfs, but he did not wait for input in the 3rd scanf. Why is that? and why did he read my second entry into the 3rd element of the array?

+3
source share
3 answers

Add getchar()afterscanf()

 for ( i = 0 ; i <= 2 ; i++ )
  { 
      printf ( "\nEnter name, price and pages: " ) ;
      k = scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;

      getchar(); //will clear the buffer
  } 

PS: Do not use scanf()for char.

+8
source

Unlike other qualifiers,% c when used with scanf does not ignore spaces. You probably want the name field strings to be anyway:

#include <stdio.h>

int main()
{ 
    struct book 
    { 
        char name[10] ;   // or some suitable size
        float price ; 
        int pages ; 
    } ;

    struct book b[3] ;
    int i ; int k;
    for ( i = 0 ; i <= 2 ; i++ )
    { 
        printf ( "\nEnter name, price and pages: " ) ;
        k = scanf ( "%s %f %d", b[i].name, &b[i].price, &b[i].pages ) ;
    } 
    for ( i = 0 ; i <= 2 ; i++ ) 
        printf ( "\n%s %f %d", b[i].name, b[i].price, b[i].pages ) ;
    return 0;
}
+7
source

fflush(stdin); ..

, fflush stdin, fflush . , fflush undefined .

int fflush(FILE *ostream);

Excerpt from standard C says:

ostream indicates an output stream or an update stream in which the most recent operation has not been entered. The fflush function calls any unwritten data for this stream, which will be delivered to the host environment, which will be written to the file; otherwise, the behavior is undefined.

0
source

Source: https://habr.com/ru/post/1757467/


All Articles