Inserting a space when printing characters using fprintf
185 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Jan
on 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')
0 Comments
More Answers (1)
Mark McBroom
on 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 Comment
Star Strider
on 20 Nov 2016
Edited: Star Strider
on 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
See Also
Categories
Find more on Interactive Control and Callbacks in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!