Saving multiple responses from a single edit text box

조회 수: 1 (최근 30일)
Shae Morgan
Shae Morgan 2015년 7월 29일
답변: HUSNU CANBOLAT 2019년 12월 29일
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.

채택된 답변

Tushar Sinha
Tushar Sinha 2015년 7월 31일
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

추가 답변 (1개)

HUSNU CANBOLAT
HUSNU CANBOLAT 2019년 12월 29일
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);

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by