在while循环中使用文本作为条件 [英] Using text as condition in a while loop
问题描述
使用文本作为while循环的条件时遇到麻烦,目前的基本编码为:
Im having some trouble with using text as an condition for a while loop, currently the basic coding is:
result=struct('val','yes');
while result.val=='yes'
result.val=input('more digits?');
end
因此,正如您所看到的,Im试图做的就是只要用户输入是"就保持循环继续进行.但这就是我所拥有的一个探秘之一.有没有一种方法可以消除写"的需要(例如,是,而不是是")?其次,当我运行代码时,它给我错误信息使用==时出错,矩阵尺寸必须一致.".我意识到这与是"比不"更长有关,但我不知道如何解决.尽管考虑到程序仍然会终止,但这并不是一个真正的问题,但这是我想要摆脱的烦恼.
So as you see, what Im trying to do is keeping the loop going as long as the user types in 'yes'. But thats one of the probelmes I am having; Is there a way to get rid of the need to write the ''(e.g yes instead of 'yes')? Secondly, when I run the code it gives me the error message "Error using == ,Matrix dimensions must agree.". I realise this have to do with the word yes being longer than no, but I don't know how to fix it. It's not really an issue though considering its the the program ends anyway, but it is an annoyance I would like to get rid off.
推荐答案
To compare strings, use strcmp
, or strcmpi
to ignore case. It will handle comparison of different length strings. For example:
strcmpi(result.val,'yes')
If you want to search for a substring, such as just a 'y', at the beginning of the input, consider strncmpi
(strncmpi(result.val,'y',1)
) or just check the first character (result.val(1)
).
这篇关于在while循环中使用文本作为条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!