Effacer les filtres
Effacer les filtres

Inserting a space when printing characters using fprintf

126 vues (au cours des 30 derniers jours)
Gesh
Gesh le 20 Nov 2016
Modifié(e) : Star Strider le 20 Nov 2016
I have an array of characters assigned to variable m20 in the format of
CGNU
AEOS
NRRA
I am supposed to have a printed output of 'CAN GER NOR USA' but I am getting 'CANGERNORUSA' with the following code
fprintf('Countries with at least 20 medals: %s \n',m20)
if I were to add 5.0 infront of the %s placeholder, my outputs just vanishes instead of printing.
How can I insert space after printing 3 characters?

Réponse acceptée

Jan
Jan le 20 Nov 2016
Str = ['CGNU'; ...
'AEOS'
'NRRA'];
CStr = cellstr(Str.'); % Transposing is important
fprintf('Countries with at least 20 medals:');
fprintf(' %s', CStr{:}); % Or: fprintf(' %c%c%c', Str)
fprintf('\n')

Plus de réponses (1)

Mark McBroom
Mark McBroom le 20 Nov 2016
You must have stripped out the spaces in m20 before printing. Either add spaces back into m20 before printing or change print statement to this:
fprintf('Countries with at least 20 medals: %3s %3s %3s %3s\n',m20(1:3), m20(4:6), ...
m20(7:9), m20(10:12));
  1 commentaire
Star Strider
Star Strider le 20 Nov 2016
Modifié(e) : Star Strider le 20 Nov 2016
@Linggeas Kisten — Please learn to use the [{}Code] button to format your code. That will help significantly.
I formatted it for you, but not in time for ‘Mark M’ to benefit from it.
m20 = ['CGNU'
'AEOS'
'NRRA'];
fprintf('Countries with at least 20 medals: ')
fprintf(1,'%c%c%c ', m20)
fprintf('\n')
Countries with at least 20 medals: CAN GER NOR USA

Connectez-vous pour commenter.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by