Saving multiple responses from a single edit text box

1 view (last 30 days)
I am trying to save multiple responses from a single edit text box each time the user pushes a "save" button. Below is my code:
function pushbutton1_Callback(hObject, eventdata, handles)
s = get(handles.edit1, 'String');
output_s = fopen('GUIDATA.txt','a');
formatspec = '%s';
fprintf(output_s,'%s',s);
fclose(output_s);
end
I'm getting a .txt file with a long string of the responses, but I'd like to eventually have a list of words that the user will hear in the first column, and the user input be saved in the second column, something like this
Target word User response
hello <user input from edit text box>
wall <user input from edit text box>
Thanks for any help in advance. I'm fairly new to Matlab and just can't seem to figure this out.

Accepted Answer

Tushar Sinha
Tushar Sinha on 31 Jul 2015
Hi Shae,
It is my understanding that you wish to format your text file such that the list of words that the user will hear appear in the first column, and the user input be saved in the second column.
You can achieve this by setting the "formatSpec" parameter of the fprintf MATLAB command. Here is a small sample code to do the same:
function pushbutton1_Callback(hObject, eventdata, handles)
s = get(handles.edit1, 'String');
st = generateRandStr; %returns a random string of length 7 or less
output_s = fopen('GUIDATA.txt','a');
formatspec = '%7s \t %s\n';
fprintf(output_s,formatspec,st,s{:});
fclose(output_s);
function st = generateRandStr %Generate a random string
symbols = ['a':'z' 'A':'Z' '0':'9'];
MAX_ST_LENGTH = 7;
stLength = randi(MAX_ST_LENGTH);
nums = randi(numel(symbols),[1 stLength]);
st = symbols (nums);
In the "pushbutton1_Callback" function, I have set the "formatspec" to "%7s \t %s\n". Here, "%7" represents the length of the longest string returned by "generateRandStr" function. You can change it to any other value as per your requirement. Also, I noticed in your code was that you are directly using the string from the "get(handles.edit1, 'String')" command in "fprintf", this will throw an error as the "get(handles.edit1, 'String')" command returns a cell rather than a string and "fprintf" expects a string parameter. Therefore, you need to use "s{:}" as a parameter in "fprintf" rather than "s". Hope this resolves the issue.
Thanks,
Tushar

More Answers (1)

HUSNU CANBOLAT
HUSNU CANBOLAT on 29 Dec 2019
ca={handles.text_bilgiler} ;
str = char(ca);
fid = fopen(strcat('test.txt'), 'w');
formatSpec = '%s\n';
[nrows,ncols] = size(str);
for row = 1:nrows
fprintf(fid,formatSpec,str(row,:));
end
fclose(fid);

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!