简体   繁体   中英

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? 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. 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!).

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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