0

My problem is: Input name and print out in the order

Ex: input the name : Martin Luther King

result : King,Martin-Luther

But when i run this code it prints out : King,LutherMartin-Luther. Can you help show me the mistake?

#include<stdio.h>
#include<conio.h>
#include <string.h>
int main()
{
char name[100];
int i;
printf("input full name: "); gets(name);
char * c =&name[strlen(name)-1];
while (*(c)!=' ')
    c--;
printf("%s,",c);
*c= '\0';
char *d=&name;
while (*(d)!=' ')
    d++;
printf("%s",d);
*d='-';
printf("%s",name);
getch();
return 0;
}
6
  • 5
    Your first printf prints "King,", second printf prints "Luther". After that, you do not set *d to NULL, you set it to '-'. At that point, name becomes "Martin-Luther\0King\0". So the last printf prints "Martin-Luther". So, your second printf is unnecessary if you're converting "X Y Z" to "Z,X-Y". Commented Apr 12, 2015 at 14:14
  • What happened to indentation and braces? Commented Apr 12, 2015 at 14:15
  • the header file conio.h is not portable. suggest removing that header file and replacing getch() with getchar() Commented Apr 12, 2015 at 14:32
  • @user3629249 thank you :) i use both visual and code block, so when i use visual i have to use conio.h Commented Apr 12, 2015 at 14:38
  • 1
    in C, the name of an array devolves to the address of the array. So this line: 'char *d=&name;' should be: 'char *d=name;' Commented Apr 12, 2015 at 14:44

2 Answers 2

1
printf("%s",d);

is the root of the problem as it results in the extra print of the middle name. Simply remove that line.

Sign up to request clarification or add additional context in comments.

Comments

0

The string is "Martin Luther King"
You Display "King" first.
Then "Martin".
Then again "Martin-Luther".

Just remove the printf at line 17.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.