How do I put spaces before a line in a txt file using strcat and fprintf?

21 views (last 30 days)
How do I put spaces before a line in a txt file using strcat and fprintf?
When I go in MATLAB and try to print ' 1,2,3' in the file opened in fid_wrt as shown below. I will find that the file has '1,2,3', without the spaces.
B{1} = '%.4f,%.4f,%.4f';
fprintf(fid_wrt,strcat(' \n',B{1},','),1:1:3);
I tried adding the spaces before \n...after it...nothing. I just can't get those spaces in the fid_wrt file. I just want those spaces before the numbers man. Whats weird is that fprintf (without writing in the file) does show those spaces in the command window!!

Accepted Answer

Stephen23
Stephen23 on 16 Apr 2023
STRCAT removes whitespace characters. The easy and robust approach is separate FPRINTF calls:
fprintf(fid_wrt,' \n')
fprintf(fid_wrt,B{1},1:1:3)
fprintf(fid_wrt,',')

More Answers (1)

Image Analyst
Image Analyst on 16 Apr 2023
strcat does an automatic trim of spaces. Just use fprintf alone. No need for B or strcat.
% Have a line with spaces on it before the line with numbers on it.
fprintf(fid_wrt,' \n%.4f, %.4f, %.4f\n', 1 : 3);
  2 Comments
Ali Almakhmari
Ali Almakhmari on 16 Apr 2023
The thing is, B{1} changes in the code...its not something that is a constant. So I need strcat to concatenate B{1} in the fprintf.
Image Analyst
Image Analyst on 16 Apr 2023
Edited: Image Analyst on 16 Apr 2023
You could put B in as a string
% Define a format specifier string using B.
B{1} = ' \n%.4f,%.4f,%.4f\n';
formatSpecifier = B{1};
% Have a line with spaces on it before the line with numbers on it.
fprintf(fid_wrt, formatSpecifier, 1 : 3);

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!