Reputation: 101
fileID = fopen('nums.txt','w'); %opens a.txt file
s = input('s = '); %requests a number as input from the keyboard
a = char(s) %converts the number to character
fprintf(fileID,'%4.4f\n',a); %prints the character (not number) in a *.txt file
The purpose is to print a character in a *.txt file, which is written as number in advance. I type the number as input, and then I convert the number to the corresponding character.
Even though matlab returns me a = ! in the Command Window, the *.txt file include the number (typed by keyboard) 33 (unconverted to the corresponding character, as it should be)
Looking forward to your generous help.
Upvotes: 2
Views: 59
Reputation: 3177
The main problem is in the fprintf()
: the %f
tag means a floating point number whereas a
appears to be a string. You need to use %s
to write a string in fprintf()
.
Let's say we type 33
, as you suggested.
According to your code, in the Command Window we'll have a=!
, which is correct, but in the .txt file we'll have 33.0000
because the fprintf()
intrinsically re-converts it back to numerical (floating point, to be precise) due to the %f
tag.
By replacing your fprintf()
with
fprintf(fileID,'%s\n',a); %prints the character (not number) in a *.txt file
the Command Window obviously will still display a=!
but this time in the .txt file we'll have !
as well.
Upvotes: 3