gpt4 book ai didi

c - 获取无限循环的问号

转载 作者:行者123 更新时间:2023-11-30 17:09:28 25 4
gpt4 key购买 nike

我正在尝试运行 Deitel 教科书“C 如何编程”中的这个简单程序,该程序扫描来自 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.)

后面是无限循环的“?”。 client.dat 文件已损坏并带有“?”人物。这里有什么问题吗?

编辑

看起来 MacOSX 上的 Ctrl+D 就可以了。

最佳答案

请尝试一下,运行良好。您的代码几乎很好,只是循环中有一点困惑。我修改了 STRICT MINIMUM 以使其运行,并给您留下了一些工作要做。将 EOF 替换为 0 ,看起来更简单,但这取决于你。

#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 */

关于c - 获取无限循环的问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33273576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com