简体   繁体   English

如何将“inputdlg”输出转换为文本文件?

[英]How to convert 'inputdlg' output into text file?

I am writing a script that displays a character array (I would use a string array but inputdlg requires char), allows the user to edit the array, and outputs the new array into a text file.我正在编写一个显示字符数组的脚本(我将使用字符串数组,但 inputdlg 需要字符),允许用户编辑数组,并将新数组输出到文本文件中。

However, I am running into the issue of not being able to format the output (vals1) into a text file.但是,我遇到了无法将输出 (vals1) 格式化为文本文件的问题。 I think part of the problem is that the inputdlg command outputs a 1x1 array, which is difficult to convert back into the line-by-line format that I started with (in this case arr).我认为问题的一部分是 inputdlg 命令输出一个 1x1 数组,它很难转换回我开始使用的逐行格式(在这种情况下为 arr)。

The code below outputs a single line read by column rather than row: "A1ReB2otC3bcD4e E5re 6tt 7 c 8S 9m ith ".下面的代码输出按列而不是行读取的单行:“A1ReB2otC3bcD4e E5re 6tt 7 c 8S 9m ith”。 I'm not sure how I would convert this since the charvals1 (the inputdlg output) returns the same string of characters.我不确定如何转换它,因为 charvals1(inputdlg 输出)返回相同的字符串。

Is there a way to either return a row-by-row output (rather than the 1x1 array string) after the user inputs a new array, or print a reformatted version of the inputdlg output (including line breaks)?有没有办法在用户输入新数组后返回逐行输出(而不是 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) ;

Don't use convertCharsToStrings, since it will operate along the first dimension of the character array (you could transpose the character array first, but then the 'linebreaks' are lost).不要使用 convertCharsToStrings,因为它将沿字符数组的第一维操作(您可以先转置字符数组,但随后会丢失“换行符”)。

You can convert the character array that you obtain to a string and then trim the whitespace.您可以将获得的字符数组转换为字符串,然后修剪空格。 This can be written to a textfile without any problem with the code that you have already.这可以写入文本文件,而您已经拥有的代码没有任何问题。

charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = string(charvals1{1}); % note the {1} to access the contents of the cell array. 
vals1 = strtrim(vals1); 

And don't forget to close the txtfile :并且不要忘记关闭txtfile

txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1);
fclose(txtfile);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM