I have 2 issues, but this is the more pressing one...
printf("Enter the term: "); scanf("%d", &input);
fprintf(inputf, "%d,", input);
printf("Enter the id: "); scanf("%d", &input);
fprintf(inputf, "%d,", input);
printf("Enter last name: "); scanf("%s", name);
fprintf(inputf, "%s,", name);
printf("Enter first name: "); fgets(name, 15, stdin);
fprintf(inputf, "%s,", name);
printf("Enter the subject: "); scanf("%s", subsec);
fprintf(inputf, "%s,", subsec);
printf("Enter the catalog number: "); scanf("%d", &input);
fprintf(inputf, "%d,", input);
//ISSUE HERE!
printf("Enter the section: "); scanf("%s", subsec);
fprintf(inputf, "%s\n", subsec);
Whenever I input all of this information and press enter on the last variable entry I get a window that says this "Run-Time Check Failure #2 - Stack around the variable 'subsec' was corrupted." I can continue and the program pretty much does what I want it to and works, but why is this happening?
My second part is when I get to entering the last name, and then want to enter the first name, it takes in the "\n" character when I press enter for the firstname string variable, obviously dont want that happening, but the both first and last name need to be capable of holding strings with whitespaces. How do I kill both birds with a single stone? I used fget to allow me to hold whitespace, but it cases my "\n" capture issue, but if I change it back to scanf, I cant hold whitespaces!
EDIT: This is subsec
char subsec[MAX_SUBSEC];
MAX_SUBSEC is set to three, I use it previously as you can see, but I figured the second scanf (the one for section, not subject) would write over the original use of inputting subsec, Im going to say I am wrong? And I am not allowed to do this, thus the issue...
Input for subject will be "CSE" and the input for section will be "R01" And yes this is all going to be put into a file.
If MAX_SUBSEC
is 3 and you enter more than 2 characters for the subject or subsection, you'll overrun the subsec
array on the stack and corrupt the stack frame (which may or may not cause problems. You should use
scanf("%2s", subsec); /* read up to two non-whitespace characters for subsec */
to ensure it doesn't try to read and store more than 2 characters (plus the trailing NUL) into subsec
You might also want to add a
scanf("%*[^\n]"); /* discard the rest of the input line */
after each scanf you have currently to discard the rest of the input line (in case some enters more than the single data item you want. You can combine the two with
scanf("%2s%*[^\n]", subsec); /* read 2 chars and discard the rest of the line */
if you want.
To enter strings of at most 15 chars (including NUL) with whitespace for first/last name, use:
scanf(" %14[^\n]", name); /* read up to 14 chars from the line */
That will discard any leading whitespace (including the newline from the previous line) and then read into name
, but won't discard trailing spaces from the name if someone enters them (you might want to clean them up).