How do I use input to make a string and fprintf to output different parts of the string?

10 次查看(过去 30 天)
I'm trying to write a program that will allow the user to enter their name as a string. And then using fprintf, output the user’s name as well as the first and last letter of the users name separately.
  3 个评论
Sydney Mukavetz
Sydney Mukavetz 2018-4-2
name=input('enter your name ') say you input brian, I want the output to be "brian" , "b" , "n" all separate
Bob Thompson
Bob Thompson 2018-4-2
编辑:Bob Thompson 2018-4-2
The portion of the input should work fine (EDIT: Nvm, listen to James answer). If you want just first and last letters then you should be able to save them as different values using indexing.
name = input('Enter your name: ');
first = name(1);
last = name(end);
fprintf('Your name is: %s %nWith first and last letters: %c and %c%n',name,first,last);
The exact syntax may be a bit off since I don't always remember the exact nuances of fprintf, but that should be pretty much what you want.

请先登录,再进行评论。

采纳的回答

James Tursa
James Tursa 2018-4-2
Use the 's' option to read the input as a string. E.g.,
name=input('enter your name ','s');
Then you can use fprintf with three different %s formats to print out name, name(1), and name(end).

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by