该代码应该将用户输入的信息打印到文件上,但是它所做的只是创建一个空文件...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct room
{
int room;
char type[9];
int cap;
int price;
}rm;
FILE *k;
int main(){
struct room rm;
k=fopen("rooms.txt","w");
printf("Please enter room number:");
scanf("%d", rm.room);
printf("\nPlease enter a description:");
scanf("%s", rm.type);
printf("\nPlease enter the room capacity:");
scanf("%d", rm.cap);
printf("\nPlease enter the price:");
scanf("%d", rm.price);
fprintf(k,"%d\t %s\t %d\t %d\n", rm.room,rm.type,rm.cap,rm.price);
fclose(k);
}
答案 0 :(得分:4)
这里
struct room
{
int room;
char type[9];
int cap;
int price;
}rm;
rm.room
,rm.cap
和rm.price
属于int
类型,在扫描用户输入时,需要o提供地址&
来存储整数进去。例如,替换此
scanf("%d", rm.room); /* to store something into rm.room need to provide address */
使用
scanf("%d", &rm.room);
还有这个
scanf("%d", rm.cap); /* address is not provided */
scanf("%d", rm.price); /* address is not provided */
使用
scanf("%d", &rm.cap);
scanf("%d", &rm.price);
还要检查fopen()
的返回类型。例如
k=fopen("rooms.txt","w");
if(k == NULL) {
/* @TODO error handling */
fprintf(stderr, "failure message\n");
return 0;
}
答案 1 :(得分:0)
以下建议的代码:
scanf()
main()
现在,建议的代码:
#include <stdio.h> // fprintf(), fopen(), fclose(), perror(), scanf()
#include <stdlib.h> // EXIT_FAILURE, exit()
struct room
{
int room;
char type[9];
int cap;
int price;
};
int main( void )
{
struct room rm;
FILE *k = fopen("rooms.txt","w");
if( !k )
{
perror( "fopen rooms.txt for writing failed" );
exit( EXIT_FAILURE );
}
printf("Please enter a room number:");
if( scanf("%d", &rm.room) != 1 )
{
fprintf( stderr,
"scanf for -room number- failed\n" );
fclose( k );
exit( EXIT_FAILURE );
}
printf("\nPlease enter a room description:");
if( scanf("%8s", rm.type) != 1 )
{
fprintf( stderr,
"scanf for -room description- failed\n" );
fclose( k );
exit( EXIT_FAILURE );
}
printf("\nPlease enter the room capacity:");
if( scanf("%d", &rm.cap) != 1 )
{
fprintf( stderr,
"scanf for -room capacity- failed\n" );
fclose( k );
exit( EXIT_FAILURE );
}
printf("\nPlease enter the room price:");
if( scanf("%d", &rm.price) != 1 )
{
fprintf( stderr,
"scanf for -room price- failed\n" );
fclose( k );
exit( EXIT_FAILURE );
}
// multi lined parameters to honor right page margin
fprintf(k,"%d\t %s\t %d\t %d\n",
rm.room,
rm.type,
rm.cap,
rm.price);
fclose(k);
}
回答OP的问题:为什么该程序无法在我的文件上打印?
由于scanf()
函数参数的语法不正确,因此所发布的代码未输入任何内容