简体   繁体   English

如何将字符转换为字符串?

[英]How to change a char into a string?

char middle;
printf("What is your middle name? ");       
scanf(" %c", &middle);      
printf("Your middle name is %c \n\n", middle); 

So I'm trying to make a simple program which ask for a name then prints it out, but it only returns a character, I know that %c is for characters, but what do I have to do to get the full name? 因此,我正在尝试制作一个简单的程序,要求输入名称然后将其打印出来,但是它只返回一个字符,我知道%c用于字符,但是我必须怎么做才能获得全名? Thanks in advance, sorry for such a stupid question, only a beginner :) 在此先感谢您,这样一个愚蠢的问题,只对初学者很感激:)

Reserve space for more than one character: 保留多个字符的空间:

char middle[32];

and scan and print strings: 并扫描和打印字符串:

if(scanf("%31s", middle) == 1)
  printf("Your middle name is %s\n, middle);

You are only getting one char, if you want a complete word, you should use "%s" as your format string. 您只得到一个字符,如果要输入完整的单词,则应使用"%s"作为格式字符串。 The following code will get you the middle name as long as you do not type more that 50 characters (try to put more than 50 characters to see what happens!). 以下代码将为您提供中间名,只要您键入的字符数不超过50个即可(尝试输入50个以上的字符以查看会发生什么!)。

char middle[50];
scanf("%s", middle);

Then to print the result: 然后打印结果:

printf("Middle name is %s", middle);
char* middle=malloc(EXPECTED_NAME_LENGTH+1);
printf("What is your middle name? ");       
scanf(" %s", middle);      
printf("Your middle name is %c \n\n", middle);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM