필터 지우기
필터 지우기

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

조회 수: 19 (최근 30일)
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!!

채택된 답변

Stephen23
Stephen23 2023년 4월 16일
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,',')

추가 답변 (1개)

Image Analyst
Image Analyst 2023년 4월 16일
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
Ali Almakhmari
Ali Almakhmari 2023년 4월 16일
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 2023년 4월 16일
편집: Image Analyst 2023년 4월 16일
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);

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by