Why does command prompt show numbers before I begin?

71 views Asked by At

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;
}
2

There are 2 answers

0
LPs On BEST ANSWER

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.

0
Sourav Ghosh On

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)