MATLAB [Matlab] How to use inputdlg string variable in text file?

AI Thread Summary
To save the input from the "inputdlg" function into a text file, the code needs a minor adjustment. The issue arises from the use of square brackets in the fprintf function, which prevents the variable from being properly formatted. Removing the square brackets allows the name to be correctly written to the file. The corrected line should read: fprintf(fileID, 'His name is %s.', name); This change ensures that the entered name appears in the text file as intended.
muaaman
Messages
4
Reaction score
0
I am trying to display the input that I enter into the dialog box from "inputdlg" function into a text file.

This is what I've so far:

Code:
prompt={['What is your name?']};
title = 'Name Machine';
answer = inputdlg(prompt, title);
name = answer{1};
fileID = fopen('NameMachineFive.txt', 'w');
fprintf(fileID,['His name is %s.', name]);
fclose(fileID);

The input dialog shows up and asks 'What is your name'? I enter it in, and then it closes. I go open the text file 'NameMachineFive.txt' and I get:

Code:
His name is

But when I enter into Matlab:

Code:
name

I get the name that I entered into the 'inputdlg' dialog box.

So my question is:

]How would I fix the code to get the name input entered into the text file?

I'd highly appreciate the assistance.
 
Physics news on Phys.org
muaaman said:
Code:
prompt={['What is your name?']};
title = 'Name Machine';
answer = inputdlg(prompt, title);
name = answer{1};
fileID = fopen('NameMachineFive.txt', 'w');
fprintf(fileID,['His name is %s.', name]);
fclose(fileID);
Remove the square brackets in the fprintf:
Matlab:
fprintf(fileID,'His name is %s.', name);
 
  • Like
Likes muaaman
Thank you very much DrClaude.
 

Similar threads

Replies
4
Views
1K
Replies
5
Views
7K
Replies
4
Views
1K
Replies
5
Views
3K
Replies
12
Views
3K
Replies
4
Views
3K
Back
Top