Reputation: 69
I am trying to develop a basic program that takes your name and provides the output in standard format. The problem is that I want the user to have an option of not adding the middle name.
For Example: Carl Mia Austin gives me C. M. Austin but I want that even if the Input is Carl Austin it should give me C. Austin without asking the user if they have a middle name or not. So, Is there a way or function which could automatically detect that??
#include <stdio.h>
int main(void) {
char first[32], middle[20], last[20];
printf("Enter full name: ");
scanf("%s %s %s", first, middle, last);
printf("Standard name: ");
printf("%c. %c. %s\n", first[0], middle[0], last);
return 0;
}
Upvotes: 3
Views: 88
Reputation: 144949
As currently written, scanf("%s %s %s", first, middle, last);
expects 3 parts to be typed and will wait until the user types them.
You want to read a line of input with fgets()
and scan that for name parts with sscanf
and count how many parts were converted:
#include <stdio.h>
int main(void) {
char first[32], middle[32], last[32];
char line[32];
printf("Enter full name: ");
fflush(stdout); // make sure prompt is output
if (fgets(line, sizeof line, stdin)) {
// split the line into parts.
// all buffers have the same length, no need to protect the `%s` formats
*first = *middle = *last = '\0';
switch (sscanf(line, "%s %s %[^\n]", first, middle, last)) {
case EOF: // empty line, unlikely but possible if stdin contains '\0'
case 0: // no name was input
printf("No name\n");
break;
case 1: // name has a single part, like Superman
printf("Standard name: %s\n", first);
strcpy(last, first);
*first = '\0';
break;
case 2: // name has 2 parts
printf("Standard name: %c. %s\n", first[0], middle);
strcpy(last, middle);
*middle = '\0';
break;
case 3: // name has 3 or more parts
printf("Standard name: %c. %c. %s\n", first[0], middle[0], last);
break;
}
}
return 0;
}
Note that names can be a bit more versatile in real life: think of foreign names with multibyte characters, or even simply William Henry Gates III
, also known as Bill Gates. The above code handles the latter, but not this one: Éléonore de Provence
, the young wife of Henry III, King of England, 1223 - 1291.
Upvotes: 7
Reputation: 26637
You could use isspace
and look for spaces in the name:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char first[32], middle[32], last[32];
int count=0;
int i = 0;
printf("Enter full name: ");
scanf(" %[^\n]s",first);
for (i = 0; first[i] != '\0'; i++) {
if (isspace(first[i]))
count++;
}
if (count == 1) {
int read = 0;
int k=0;
for (int j = 0; j < i; j++) {
if (isspace(first[j]))
read++;
if (read > 0) {
last[k]=first[j];
k++;
}
}
last[k+1] = '\0';
}
printf("Standard name: ");
printf("%c. %s\n", first[0], last);
return 0;
}
Test
Enter full name: Carl Austin
Standard name: C. Austin
Upvotes: 0