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

Click For Summary
SUMMARY

The discussion focuses on using the MATLAB function "inputdlg" to capture user input and write it to a text file. The original code attempts to format the output incorrectly, resulting in an empty string in the text file. The solution provided involves removing square brackets from the "fprintf" function, changing it to "fprintf(fileID,'His name is %s.', name);" which correctly formats the string and outputs the user input to the specified text file "NameMachineFive.txt".

PREREQUISITES
  • Familiarity with MATLAB programming language
  • Understanding of the "inputdlg" function in MATLAB
  • Knowledge of file handling in MATLAB, specifically "fopen" and "fprintf"
  • Basic string formatting techniques in MATLAB
NEXT STEPS
  • Explore advanced file I/O operations in MATLAB
  • Learn about error handling in MATLAB file operations
  • Investigate user input validation techniques in MATLAB
  • Study string manipulation functions in MATLAB for more complex formatting
USEFUL FOR

MATLAB developers, data analysts, and anyone looking to enhance their skills in user input handling and file operations within MATLAB.

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   Reactions: muaaman
Thank you very much DrClaude.
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 5 ·
Replies
5
Views
7K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 12 ·
Replies
12
Views
4K
Replies
1
Views
2K
Replies
1
Views
5K