My C program is suppose to receive a full name separated by a comma. Example output is below:
Enter input string:
Jill, Allen
First word: Jill
Second word: Allen
Enter input string:
Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string:
Washington,DC
First word: Washington
Second word: DC
Enter input string:
q*
However, with my current code, Jill, Allen
works as intended but the other two names do not work properly as the first letter is missing. I think this happens because of the input format. Every name is separated by a new line so the machine doesn't read the terminating line and thus ignores the first letter. This is how my code looks right now when outputted:
Enter input string:
Jill, Allen
First word: Jill
Second word: Allen
Enter input string:
Golden , Monkey
First word: olden
Second word: ,
Enter input string:
Washington,DC
First word: ashington
Second word: ,
As you can see the first letter in First word is missing which then messes up Second word. Any advice would be appreciated thanks. My code:
#include<stdio.h>
#include <string.h>
int main(void) {
char name[100];
char firstName[100];
char lastName[100];
char comma = ',';
char quit;
int i;
while(quit != 'q')
{
printf("Enter input string:\n");
fgets(name, 100, stdin);
scanf("%c", &quit);
if(!(strchr(name, comma)))
{
printf("Error: No comma in string.\n\n");
}
if((strchr(name, comma)))
{
sscanf(name, "%s%s", firstName, lastName);
for(i = 0; i < strlen(name); i++)
{
if(firstName[i] == ',')
{
firstName[i] = '\0';
}
}
printf("First word: %.10s\n", firstName);
printf("Second word: %.10s\n\n", lastName);
}
}
printf("Enter input string:\n");
return 0;
}