Is there a way to have a variable value equal to text? Trying to display a user-chosen word in the middle of an fprintf line

时间:2019-04-17 00:18:31

标签: matlab octave

I am trying to code a MadLibs-type game in Octave on a Mac, and can't figure out how to display a user-chosen WORD in the middle of a string of text. I used fprintf to display the sentence with the variable in the middle and it works just fine as long as the variable is equal to a NUMBER. If you enter anything other than a number you get an error.

    Word=input('Enter a word:            ');
    fprintf('You chose %d as the word.\n', Word)

How would I allow the user to chose a word, then display that word in the middle of a string of text?

Thanks in advance.

2 个答案:

答案 0 :(得分:2)

Input可以选择将输入的文本作为MATLAB字符串返回,而无需计算表达式。

STR = input(PROMPT,'s')

这样输入的内容将作为字符串输出。 例如:

Word=input('Enter a word:            ','s');
fprintf('You chose %d as the word.\n', Word)

数字或文本将正确显示。

答案 1 :(得分:1)

The format specifier for strings is %s thus you can change your snippet to:

fprintf('You chose %s as the word.\n', Word)