Search code examples
cstringfgets

How can I use fgets to scan from the keyboard a formatted input (string)?


I need to use fgets to get a formatted input from the keyboard (i.e., student number with a format 13XXXX). I know with scanf this could be possible, but I'm not too sure with fgets. How can I make sure that the user inputs a string starting with 13?

printf ( ">>\t\tStudent No. (13XXXX): " );
fgets ( sNum[b], sizeof (sNum), stdin);

EDIT: sNum is the string for the student number. Thanks.


Solution

  • Your call to fgets() is probably wrong.

    char line[4096];
    char student_no[7];
    
    printf(">>\t\tStudent No. (13XXXX): ");
    if (fgets(line, sizeof(line), stdin) == 0)
        ...deal with EOF...
    if (sscanf(line, "%6s", line) != 1)
        ...deal with oddball input...
    if (strlen(student_no) != 6 || strncmp(student_no, "13", 2) != 0)
        ...too short or not starting 13...
    

    You can apply further conditions as you see fit. Should the XXXX be digits, for example? If so, you can convert the string to an int, probably using strtol() since tells you the first non-converted character, which you'd want to be the terminating null of the string. You can also validate that the number is 13XXXX by dividing by 10,000 and checking that the result is 13. You might also want to look at what comes after the first 6 non-blank characters (what's left in line), etc.