-1

The command prompt shows numbers before program begins. Why? 2687688 is given but the numbers won't write to file?

#include <stdio.h>
#include <conio.h>

int main(void){
    FILE*nfPtr;
    int n;
    if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","w"))==NULL)
{
    printf ("Sorry! The file cannot be opened\n");
}
    else
{//else 1 begin

    printf("Enter numbers to be stored in file\n");
    printf("%d",&n);
    while (!feof(stdin)){
          fprintf(nfPtr,"%d",n);
          scanf("%d",&n);
          }
}//else 1 ends
        fclose(nfPtr);

getch();
return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Raphael Jones
  • 115
  • 2
  • 12

2 Answers2

2

Apart from other issues, in your code

 printf("%d",&n);

is absolutely wrong and invokes undefined behaviour. . Maybe you meant

 scanf("%d",&n);

to scan-in the number.

That said, please see, why you should refrain from using !feof(file)

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

Substitute

printf("%d",&n);

with

scanf("%d",&n);

printf Writes the C string pointed by format to the standard output (stdout)

scanf Reads data from stdin

In your code you are printing n, that is not initialized, that a random number is printed out after "Enter numbers to be stored in file" string.

LPs
  • 16,045
  • 8
  • 30
  • 61