Just The 1st Character
If you really just want the first character, then *line
will provide you with the first character from each line. It is equivalent to line[0]
and you can use either interchangeably. A short example would be:
#include <stdio.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
int main (int argc, char **argv) {
char buf[MAXC];
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (fgets (buf, MAXC, fp))
printf ("'%c'\n", *buf);
if (fp != stdin) /* close file if not stdin */
fclose (fp);
Example Use/Output
$ ./bin/fgets_sscanf_first dat/multivals.txt
'3'
'1'
'2'
'V'
'H'
You can save and then test whether the first character is a digit with isdigit(*line)
(or as above isdigit(*buf)
). With a single digit, you can subtract '0'
to get the numeric value. See ASCII Table
Separating All Values
You can use sscanf
to separate one or all values in the line by attempting to parse all 3-values from the line and then checking the return to know whether you had a line with parenthesis (return of 3) or a single character (return of 1). You can use a format string of " %c(%d,%d"
(the space before "%c"
ensures leading whitespace is ignored). You can either use if/else
or a simple switch
statement to handle the different cases, e.g.
#include <stdio.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
int main (int argc, char **argv) {
char buf[MAXC];
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (fgets (buf, MAXC, fp)) {
char c;
int v1, v2;
switch (sscanf (buf, " %c(%d,%d", &c, &v1, &v2)) {
case 1 : printf ("single char/digit: '%c'\n", c);
break;
case 3 : printf ("all values: %c %d %d\n", c, v1, v2);
break;
default : fputs ("invalid line format\n", stderr);
}
}
if (fp != stdin) /* close file if not stdin */
fclose (fp);
}
Example Use/Output
$ ./bin/fgets_sscanf_multival dat/multivals.txt
all values: 3 3 3
all values: 1 5 4
all values: 2 7 7
single char/digit: 'V'
single char/digit: 'H'
There are many, many ways to do this, and this is just one. Look over all your answers and let me know if you have further questions.