Reputation: 11
This code is supposed to print the information entered by the user onto a file, but all it does is create an empty file...
#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);
}
Upvotes: 1
Views: 74
Reputation: 16540
the following proposed code:
scanf()
main()
and now, the proposed code:
#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);
}
in answer to the OPs question: Why is this program not printing on my file?
Because nothing is being input by the posted code, due to the incorrect syntax for the scanf()
function parameters
Upvotes: 0
Reputation: 11921
Here
struct room
{
int room;
char type[9];
int cap;
int price;
}rm;
rm.room
, rm.cap
and rm.price
are of int
type, while scanning input from user, you need o provide the address &
to store an integer into it. For e.g Replace this
scanf("%d", rm.room); /* to store something into rm.room need to provide address */
with
scanf("%d", &rm.room);
and this
scanf("%d", rm.cap); /* address is not provided */
scanf("%d", rm.price); /* address is not provided */
with
scanf("%d", &rm.cap);
scanf("%d", &rm.price);
Also check the return type of fopen()
. for e.g
k=fopen("rooms.txt","w");
if(k == NULL) {
/* @TODO error handling */
fprintf(stderr, "failure message\n");
return 0;
}
Upvotes: 4