For a more complete approach to line-based to address the above concerns (safe input, and embedded spaces), consider the following extended strategy and adjust for your use case:
1. read an entire input line
2. if the line is too long, abort with an error
3. parse the line
4. if the line does not contain the expected data, abort with an error
5. print the result
Here is an example (breaking into functions would help in a real program):
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10000
static char inputline[MAX] = "";
int main(void)
{
// (optional) show prompt
printf("%s", "Enter your name using the format: LAST, FIRST.\n"
"LAST and FIRST are allowed to have embedded spaces in them.\n"
": ");
// get inputline and handle errors
fgets(inputline, MAX, stdin);
size_t len = strlen(inputline);
if (len == 0) {
printf("No line received.\n");
return EXIT_FAILURE;
}else if(len == MAX-1){
printf("Line is too long.\n");
return EXIT_FAILURE;
}
// parse the inputline into LAST, FIRST
char last[100]="", first[100]="", leftover[10000]="";
if (sscanf(inputline, " %99[^,], %99[^.].%9999c", last, first, leftover) != 3) {
printf("Name was in the wrong format.\n");
return EXIT_FAILURE;
}
len = strlen(leftover);
if (len > 1) {
leftover[len-1] = '\0'; // chomp the \n from leftover
printf("Warning: trailing characters found after inputline: \"%s\"\n", leftover);
}
// show result
printf("\nLast name: \"%s\"\n", last);
printf("First name: \"%s\"\n", first);
return EXIT_SUCCESS;
}
Explanations:
scanf returns the number of items it found, so in this case 3 should be expected for correct input. If the input was correct, leftover should contain "\n" (only the newline).
%99[^,], means to get at most 99 non-commas followed by a comma. Change the size and delimiter to what you need. Example: if you use ; and the buffer for that component is 1000 characters, use %999[^;];