Printing a variable within an input command

29 次查看(过去 30 天)
I am trying to use an input command to tell a specific player that it is there turn to make a move.
My code looks like this:
move = input(['Player ' current_player ', choose column 1-7 to drop a chip: ']);
The output looks like this:
Player , choose column 1-7 to drop a chip:
Can someone help me get this working correctly?

回答(2 个)

Star Strider
Star Strider 2019-11-11
Assuming ‘current_player’ is a character array or string variable:
move = input(sprintf('Player %s, choose column 1-7 to drop a chip: ', current_player));
Otherwise, choose the appropriate format descriptor in formatSpec for the ‘current_player’ variable class.

Image Analyst
Image Analyst 2019-11-11
I think current_player is an integer, and that's why when you create a string like this:
['Player ' current_player ', choose column 1-7 to drop a chip: ']
it's making non-printable characters. Like if current_player was some number less than ASCII 32. You need to use %d or num2str
move = input(sprintf('Player %s, choose column 1-7 to drop a chip: ', current_player));
Alternatively if you don't like sprintf() for some reason, you can use brackets, quotes, and num2str() to create a character array
userPrompt = ['Player ', num2str(current_player), ' choose column 1-7 to drop a chip: '];
move = input(userPrompt);

类别

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