Azzera filtri
Azzera filtri

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

19 visualizzazioni (ultimi 30 giorni)
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!!

Risposta accettata

Stephen23
Stephen23 il 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,',')

Più risposte (1)

Image Analyst
Image Analyst il 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 Commenti
Ali Almakhmari
Ali Almakhmari il 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 il 16 Apr 2023
Modificato: Image Analyst il 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);

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by