0

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.

Sakamoto
  • 155
  • 2
  • 2
  • 14
  • Can you show some more code What is snum? Typically you'll want to say fgets(something, sizeof(something), stdin) and then usually check the return value from fgets. – dcaswell Aug 25 '13 at 06:00

4 Answers4

1

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

bazza
  • 7,580
  • 15
  • 22
1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0
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.+".

Community
  • 1
  • 1
lulyon
  • 6,707
  • 7
  • 32
  • 49
0

Sounds like you're looking for fscanf.

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

R.D.
  • 2,471
  • 2
  • 15
  • 21