Reputation: 39
I have tried this code on my device, and it creates a file named "hello.usr" and prints the text "Hello world!" successfully.
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!");
fclose(opening);
printf("Writing to the file was successful.\n");
printf("Closing the program");
return 0;
}
But the online judge where I'm submitting this program gives me an error. Your program's output is shorter than expected
How can I overcome this?
A comment says:
Write a program that prints the text "Hello world!" into the file "hello.usr". The file does not exist, so it must be created. Finally, the program must print a message on the screen indicating that writing to the file was successful. The text printed to the file must exactly match the assignment. Example output: Writing to the file was successful. Closing the program. The output of the program must be exactly the same as the example output (the most strict comparison level).
Upvotes: 0
Views: 451
Reputation: 115
I'm not sure what you mean by online judge, but it's a good thing to use "\n
" at the end of your writes. "\n
" is the special character that jumps a line.
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!\n"); // Here
fclose(opening);
printf("Writing to the file was successful. Closing the program");
return 0;
}
Reading your comment now, I don't think the solution is related to "\n
"'s.
Some other good things you should consider are:
If I was going to write the same things, I'd do like this:
#include<stdio.h>
int main() {
FILE* file = fopen("hello.usr", "w");
fprintf(file, "Hello world!");
fclose(file);
printf("Writing to the file was successful. Closing the program.");
return 0;
}
Upvotes: 1