Your program has undefined behavior because the arrays are too short and scanf()
stores the user input beyond the end of the arrays, especially the last one, section
that can only contain an empty string which scanf()
cannot read anyway.
Make the arrays larger and tell scanf()
the maximum number of characters to store before the null terminator, ie: the size of the array minus 1.
Here is a modified version:
#include <stdio.h>
int main() {
char name[50], department[50], section[50];
printf("enter the name of the student:");
if (scanf("%49s", name) != 1)
return 1;
printf("enter your department:");
if (scanf("%49s", department) != 1)
return 1;
printf("enter the section");
if (scanf("%49s", section) != 1)
return 1;
printf("Name:%s
Department:%s
Section: %s
", name, department, section);
return 0;
}
Note that using scanf
with a %s
conversion requires that each data item be a single word without embedded spaces. If you want name, department and section to accommodate spaces, which is more realistic for anyone besides Superman Krypton A
, you would use %[
]
with an initial space to skip pending whitespace and newlines (or fgets()
but in another chapter):
#include <stdio.h>
int main() {
char name[50], department[50], section[50];
printf("enter the name of the student:");
if (scanf(" %49[^
]", name) != 1)
return 1;
printf("enter your department:");
if (scanf(" %49[^
]", department) != 1)
return 1;
printf("enter the section");
if (scanf(" %49[^
]", section) != 1)
return 1;
printf("Name:%s
Department:%s
Section: %s
", name, department, section);
return 0;
}
scanf(" %49[^
]", name)
means skip any initial whitespace, including pending newlines from previous input, read and store and bytes read different from newline, up to a maximum of 49 bytes, append a null byte and return 1 for success, 0 for conversion failure or EOF
is end of file is reached without storing any byte. For this particular call, conversion failure can happen if there is an encoding error in the currently selected locale.