我创建了一个函数:
function display_book(x)
[a,b] = strtok(x,',') ;
[b,c] =strtok(b,',');
b=strrep(b,',',' ');
c=strrep(c,',',' ');
fprintf('Title : %s \n',a);
fprintf('Author :%s \n',b);
fprintf('Number of pages :%s \n',c);
end
它基本上显示了标题作者和由分隔符分隔的用户字符串输入的页数。 例如:
display_book('MATLAB 101, ATTAWAY CALMS, 115')
Title: MATLAB 101
Author: ATTAWAY CALMS
Number of Pages: 115
我跟着一个不同的代码,我调用了display_book函数:
function library
x=input(' What would you like to do : ','s');
while strcmpi('quit',x) ~= 1
Q=input(' Please create a book with a title, author and number of pages:
','s');
display_book(Q);
fprintf('The %s has been added to your library \n',Q);
x=input(' \n What would you like to do: ','s');
if strcmpi('list books',x) == 1
end
end
disp('Good-Bye')
end
所以到目前为止,当我调用我的库函数时,它允许我显示书籍,直到我进入退出以停止代码。
但是,我希望改进代码并能够列出我输入的书籍。如果我在退出图书馆之前输入了两本书,我希望能够看到我输入的书籍。
示例:
list_books
What would you like to do: list books
Title: The Hobbit
Author: J. R. R. Tolkien
Number of Pages: 454
Title: Harry Potter and the Cursed Child
Author: J. K. Rowling
Number of Pages: 245
我需要一些帮助来弄清楚如何将输入“存储”到我的库函数中。
答案 0 :(得分:0)
您可以将标题,作者,页面数量存储在单元格数组中,然后在必要时访问其成员:
function myScript() %this will create an empty cell array, push some books and list them
myLibrary={};
myLibrary=save_book('MATLAB 101, ATTAWAY CALMS,115',myLibrary);
myLibrary=save_book('some bad book, me,123',myLibrary);
list_books(myLibrary);
end
function [lib]=save_book(x,lib) %saves a book to library
[a,b] = strtok(x,',') ;
[b,c] =strtok(b,',');
b=strrep(b,',',' ');
c=strrep(c,',',' ');
lib=[lib; {a,b,c}];
end
function list_books(library) %lists books in library
for i=1:1:size(library,1)
fprintf('Title : %s \n',library{i,1});
fprintf('Author :%s \n',library{i,2});
fprintf('Number of pages :%s \n\n',library{i,3});
end
end