[英]How to convert 'inputdlg' output into text file?
我正在编写一个显示字符数组的脚本(我将使用字符串数组,但 inputdlg 需要字符),允许用户编辑数组,并将新数组输出到文本文件中。
但是,我遇到了无法将输出 (vals1) 格式化为文本文件的问题。 我认为问题的一部分是 inputdlg 命令输出一个 1x1 数组,它很难转换回我开始使用的逐行格式(在这种情况下为 arr)。
下面的代码输出按列而不是行读取的单行:“A1ReB2otC3bcD4e E5re 6tt 7 c 8S 9m ith”。 我不确定如何转换它,因为 charvals1(inputdlg 输出)返回相同的字符串。
有没有办法在用户输入新数组后返回逐行输出(而不是 1x1 数组字符串),或者打印 inputdlg 输出的重新格式化版本(包括换行符)?
arr = char(["ABCDE";
"123456789";
"Robert Smith";
"etc etc"])
% User updates the array
prompt = {'Update content below if necessary'};
dlgtitle = "Section 2";
dims = [30 50];
definput = {arr};
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = convertCharsToStrings(charvals1);
% Outputting the updated array to text file
prompt = {'Enter desired input file name'};
dlgtitle = "Input Name";
dims = [1 35];
definput = {'Input Name'};
fileName = inputdlg(prompt,dlgtitle,dims,definput);
selected_dir = uigetdir();
fileLocation = char(strcat(selected_dir, '\', string(fileName(1)),'.txt'));
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1) ;
不要使用 convertCharsToStrings,因为它将沿字符数组的第一维操作(您可以先转置字符数组,但随后会丢失“换行符”)。
您可以将获得的字符数组转换为字符串,然后修剪空格。 这可以写入文本文件,而您已经拥有的代码没有任何问题。
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = string(charvals1{1}); % note the {1} to access the contents of the cell array.
vals1 = strtrim(vals1);
并且不要忘记关闭txtfile
:
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1);
fclose(txtfile);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.