该代码应该将用户输入的信息打印到文件上,但是它所做的只是创建一个空文件...
#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);
}
这里
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句