简体   繁体   中英

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.

However, I am running into the issue of not being able to format the output (vals1) into a text file. 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).

The code below outputs a single line read by column rather than row: "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.

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)?

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).

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 = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1);
fclose(txtfile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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