Effacer les filtres
Effacer les filtres

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

19 vues (au cours des 30 derniers jours)
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!!

Réponse acceptée

Stephen23
Stephen23 le 16 Avr 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,',')

Plus de réponses (1)

Image Analyst
Image Analyst le 16 Avr 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 commentaires
Ali Almakhmari
Ali Almakhmari le 16 Avr 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 le 16 Avr 2023
Modifié(e) : Image Analyst le 16 Avr 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);

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by