Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- input_string_and_integer_into_structure_v1.c
- How to input string and integer into structure.
- Under the comments are problematic solutions.
- Best solutions are active, not commented.
- https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include<stdio.h>
- #define LEN 20 // If we use this number in several places,
- // this is a good way to define it only in one place in the program.
- struct student
- {
- int roll_number;
- char name[20];
- };
- int main(void)
- {
- struct student s1;
- printf("\n Enter your student name: ");
- //gets(s1.name); // string is without &, or:
- //scanf("%[^\n]", s1.name); // or better, to avoid buffer overflow:
- fgets(s1.name, 20, stdin); // it will input maximum LEN-1 characters of name
- // and add '\0' at end
- // If the attempted name entry is longer than LEN, we must empty the input buffer:
- // fflush(stdin); // flushes the input buffer of a stream,
- // but gives undefined behavior. Alternative is:
- // while ( ( getchar() ) != EOF && c != '\n' );
- // or:
- while ( ( getchar() ) != '\n' );
- printf("\n\n Enter your student roll number: ");
- scanf("%d",&s1.roll_number); // required &
- printf("\n\n Student detailed are: \n");
- printf("\n name: %s \n\n roll number: %d \n\n", s1.name, s1.roll_number );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement