I am using a Macbook. I have created a file using text edit, and have written the numbers 3 and 4 on it with a space in between. I saved this file called 'mydata', which then produced 'mydata.rtf'. I then changed this files name to 'mydata.txt'. I have then created this program to open this file, and then print the values within the file 'mydata.txt'. However, it is printing the values: a = 446595126, b = 32767.
Could someone please explain why this program doesn't print 3 and 4. Thank you.
#include<stdio.h>
int main(void)
{
int a, b;
FILE *fptr1;
fptr1 = fopen ( "mydata.txt", "r" );
if (fptr1 == NULL )
{
printf("FILE mydata.txt did not open\n");
}
else
{
fscanf(fptr1,"%d%d",&a,&b);
printf("a = %d, b = %d\n",a,b);
}
fclose(fptr1);
return 0;
}
答案 0 :(得分:2)
Your file is RTF (Rich Text Format), no matter the extension it has: you've simply renamed it, not converted to a different format.
The reason why you see those values is because the first characters of your file does not correspond with the numbers you entered in the editor but with the first bytes of the RTF format.
As a solution, open the file with TextEdit again and save it with a plain text format instead. You can take a look at this post too.
In general, avoid using editors that supports rich format (TextEdit, Word, Pages) for creating plain text files. Instead, use other ones like BBEdit, TextWrangler (although I think it's discontinued), emacs, Atom, vim, nano, etc.
答案 1 :(得分:0)
the reason behind it is you have included space between the two numbers and a space is a character which has ascii value of 32.. so try ommiting space while reading number from file. This may work :-)