Search code examples
cfiletext

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.

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 leads to incorrect output.

    You should just drop the & operator.

    It should be:

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

    instead of:

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

    BTW: you did it right in fprintf(fptr,"%d",num).