Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with writing to a text file in C using printf()

I’m trying to write to a file in C, so quite simple stuff. But I am encountering an issue with the below code:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    FILE *fptr;
    int num;

    fptr = fopen("C:\\test.txt","w");

    if(fptr == NULL)
    {
        printf("Error!");
        exit(1);
    }

    printf("Enter your number");
    scanf("%d",&num);
    printf("Your number is: %d",&num);
    fprintf(fptr,"%d",num);

    fclose(fptr);

    return 0;
}

It never prints the value of num, and the text file always just ends up with an incorrect value.

I’ve tried over and over again to fix the problem, changing the values I put into it, trying to fiddle around the with the MGM compiler I am using to see if it’s a compiler issue, to no avail. I’ve even tried copying other C code that writes to text files, only to get the same issue.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It always just writes 0.
When I run it, it looks like this –

Enter your number3
3
Your number is: 3

But the value being entered is always 0.

>Solution :

The printf function expects the value of num itself, not the address of num. Passing the address of num causes undefined behavior, which may lead to incorrect output.
You have used the wrong format string in printf, and it should be:

printf("Your number is: %d", num);

instead of:

 printf("Your number is: %d", &num);

 ```
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading