I have a problem with \n
when I am trying to write a datestring and number values in txt file
pattern = [ ...
'Date %s - First %d \n', ...
'Date %s - Second %d \n' ...
'%d, \n', ...
'*ENDDO\n\n'];
t = datetime('now');
[fid, msg] = fopen('date_and_values.txt', 'wt');
assert(fid ~= -1, 'Cannot open file %s: %s', 'долбоеб.txt', msg);
formatOut='dd.mm.yy';
dateString = datestr(t);
disp(dateString);
formatNumb = '\t%d';
res = [dateString num2str(1,formatNumb) num2str(2,formatNumb)];
for k = 1:17
fprintf(fid, pattern, res);
% % Perhaps this is faster:
% % fwrite(fid, strrep(pattern, '%d', sprintf('%d', k)), 'char');
end
fclose(fid);
I want the data looks like this:
But instead I get data in file look like this:
What am I doing wrong?
CodePudding user response:
Change pattern
to
pattern = ['Date %1$s - First %2$d \n', ...
'Date %1$s - Second %3$d \n\n'];
and use
fprintf(fid, pattern, dateString, num2str(1,formatNumb), num2str(2,formatNumb));
instead, you will get the desired output.
Note the use of identifiers in the above. (ctrl F "identifiers" in documentation.) Without identifiers, each time you have a new formatting operator, a new input is expected by fprintf()
. On top of that, every uniquely identified operator in your pattern should correspond to 1 input in fprintf()
.
(The pattern in OP also contains some superfluous trailing bits that are not found in the example output.)
CodePudding user response:
I don't know if I understand what you are looking for, but, have you tried this?
res = [dateString num2str(1,formatNumb) num2str(2,formatNumb) '\n'];