I'm making a program that takes names from the user seperated by commas. The program allows the user to put as many or as little spaces as they want between the commas. So for example:
If I were to type something like
Smith, John
or
Smith,John
I would want to print out
John, Smith
The thing is though my program does not properly process the following examples above; it works if the input was something like
Smith , John
or
Smith ,John.
Here is my code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LINESIZE 128
int get_last_first(FILE *fp);
int main (void)
{
get_last_first(stdin);
}
/*takes names in the format [LASTNAME],[FIRSTNAME]*/
int get_last_first(FILE *fp)
{
char first[LINESIZE];
char last[LINESIZE];
char line[LINESIZE];
size_t i;
while(1)
{
printf("Enter your last name followed by a comma and your first name\n");
/*if we cant read a line from stdin*/
if(!fgets(line, LINESIZE, fp))
{
clearerr(stdin);
break; /*stop the loop*/
}
/*goes through the line array and checks for non-alphabetic characters*/
for(i = 0; i < strlen(line); i++)
{
if(!isalpha(line[i]))
{
/*if it sees a space hyphen or comma, it continues the program*/
if((isspace(line[i]) || line[i] == ',') || line[i] == '-' )
{
continue;
}
else
{
return -1;
}
}
}
if(sscanf(line, "%s , %s", last, first))
{
printf("%s, %s", first, last);
return 1;
}
return 0;
}
}
Is it because I am not using sscanf properly?
sscanf()
doesn't do pattern matching; a comma is a perfectly valid non-whitespace string component, so will be swallowed by a %s
specification. You can use something like %[^ \t,]
to match a run of characters up to whitespace or a comma.