So I'm writing a program that takes a persons name and splits it into their first and last name so for example if you enter JonSnow it should print: First: Jon Last: Snow
This is the code, please ignore the comments, I was testing a bunch of different ways to do it.
#include <stdio.h>
#include <string.h>
int main()
{
char name[50],first[25],last[25];
int i;
printf("What is your name? ");
scanf("%s",name);
strcpy(first," ");
strcpy(last," ");
for(i=0;i<strlen(name);i++){
strcat(first,name[i]); //for(j=i+1;strlen(name);j++){
if(name[i+1]>=65 && name[i+1]<=90){
strcat(last,name[i]);
strcat(last,name[i+1]);
}
//}
}
printf("First name: %s \n",first);
printf("Last name: %s \n",last);
}
When I run it in the terminal, I get this:
What is your name? JonSnow
Segmentation fault (core dumped)
What is the problem, please help...
if(name[i+1]>=65 && name[i+1]<=90){is ok, but isupper is a lot more readable/directly understandable.first, and from this index to the end tolast.%sinscanf()to prevent buffer overflow:scanf("%49s",name);.