What's in a name?
A name is usually thought of as containing letters, maybe spaces and some other characters. Code needs to be told what char
make up a name, what are valid delimiters and handle other unexpected char
.
"%s"
only distinguishes between white-space and non-white-space. It treats ,
the same as letters.
"%width[A-Za-z' ]"
will define a scanset accepting letters, '
and space. It will read/save up to width
characters before appending a null character.
Always a good idea to check the return value of a input function before using the populated objects.
FILE *fp = fopen("1.txt", "rt");
if (fp == NULL) Handle_Error();
// end-of-file signal is not raised until after a read attempt.
// while (!feof(fp)) {
char name_in[100];
char delimiter[2];
int count;
while ((count = fscanf(fp, "%99[A-Za-z' ]%1[,\n]", name_in, delimiter)) == 2) {
printf("<%s>%s", name_in, delimiter);
addnewnode(head, name_in);
if (delimiter[0] == '\n') {
; // Maybe do something special at end-of-line
}
}
fclose(fp);
// Loop stopped unexpectedly
if (count != EOF || !feof(fp)) {
puts("Oops");
}
More robust code would read the line like with fgets()
and then process the string. Could use similar code as above but with sscanf()
To include -
in a scanset so code can handle hyphenated names, list it first. You may want to allow other characters too.
"%width[-A-Za-z' .]"