我正在尝试从Deitel的教科书“C How to Program”中运行这个简单的程序,它扫描来自stdin的输入并将它们放在一个文件中。
#include <stdio.h>
int main( void )
{
int account; /* account number */
char name[ 30 ]; /* account name */
double balance; /* account balance */
FILE *cfPtr; /* cfPtr = clients.dat file pointer */
/* fopen opens file. Exit program if unable to create file */
if ( ( cfPtr = fopen( "clients.dat", "w" ) ) == NULL ) {
printf( "File could not be opened\n" );
} /* end if */
else {
printf( "Enter the account, name, and balance.\n" );
printf( "Enter EOF to end input.\n" );
printf( "? " );
scanf( "%d%s%lf", &account, name, &balance );
/* write account, name and balance into file with fprintf */
while ( !feof( stdin ) ) {
fprintf( cfPtr, "%d %s %.2f\n", account, name, balance );
printf( "? " );
scanf( "%d%s%lf", &account, name, &balance );
} /* end while */
fclose( cfPtr ); /* fclose closes file */
} /* end else */
return 0; /* indicates successful termination */
} /* end main */
当我输入此输入
时Enter the account, name, and balance. Enter EOF to end input.
? 100 Jones 24.98
? 200 Doe 345.67
? 300 White 0.00
? 400 Stone -42.16
? 500 Rich 224.62
? EOF
????????????????????..........(cont.)
接下来是“?”的无限循环。 clients.dat文件已损坏为“?”字符。这有什么问题?
修改
似乎MacOSX上的Ctrl + D可以解决问题。
答案 0 :(得分:0)
请试试这个,它运行正常。你的代码几乎是好的,只是循环中的一个小混乱。我修改了STRICT MINIMUM以使其运行,我给你留下了一些工作要做。用0取代EOF似乎更简单,但这取决于你。
#include
int main( void )
{
int account; /* account number */
char name[30]; /* account name */
double balance; /* account balance */
FILE *cfPtr; /* cfPtr = clients.dat file pointer */
/* fopen opens file. Exit program if unable to create file */
if ( ( cfPtr = fopen( "clients.dat", "w" ) ) == NULL )
{
printf( "File could not be opened\n" );
return ( 0 );
} /* end if */
// else {
while ( 1 )
{
printf( "Enter the account, name, and balance.\n" );
printf( "Enter 0 to end input.\n" );
printf( "? " );
scanf( "%d%s%lf", &account, name, &balance );
if ( account == 0 )
break;
/* write account, name and balance into file with fprintf */
//while ( !feof( stdin ) ) {
fprintf( cfPtr, "%d %s %.2f\n", account, name, balance );
//printf( "? " );
// scanf( "%d%s%lf", &account, name, &balance );
} /* end while */
fclose( cfPtr ); /* fclose closes file */
} /* end else */