简体   繁体   中英

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 (ie, 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.

Use fgets to get a string, then sscanf to interpret it. A format string of %i will interpret the string as a number. The return value from sscanf will tell you whether that interpretation was successful (ie the user typed in a number). Once you know that then divide that number by 10,000. If the result is 13 then you know the number typed in was in the range 13x,xxx

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.

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

The sNum[b] should be sNum, which is a pointer.

And after getting a line from stdin with fgets, you can check the line with regular expression : "^13.+" .

听起来你在寻找fscanf

int fscanf ( FILE * stream, const char * format, ... );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM