Advertisement
dmilicev

input_string_and_integer_into_structure_v1.c

May 21st, 2020
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.42 KB | None | 0 0
  1. /*
  2.  
  3.     input_string_and_integer_into_structure_v1.c
  4.  
  5.     How to input string and integer into structure.
  6.     Under the comments are problematic solutions.
  7.     Best solutions are active, not commented.
  8.  
  9.     https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
  10.  
  11.  
  12.     You can find all my C programs at Dragan Milicev's pastebin:
  13.  
  14.     https://pastebin.com/u/dmilicev
  15.  
  16. */
  17.  
  18. #include<stdio.h>
  19.  
  20. #define LEN 20  // If we use this number in several places,
  21.                 // this is a good way to define it only in one place in the program.
  22.  
  23. struct student
  24. {
  25.     int roll_number;
  26.     char name[20];
  27. };
  28.  
  29. int main(void)
  30. {
  31.     struct student s1;
  32.  
  33.     printf("\n Enter your student name: ");
  34.     //gets(s1.name);    // string is without &, or:
  35.     //scanf("%[^\n]", s1.name); // or better, to avoid buffer overflow:
  36.  
  37.     fgets(s1.name, 20, stdin);  // it will input maximum LEN-1 characters of name
  38.                                 // and add '\0' at end
  39.  
  40.     // If the attempted name entry is longer than LEN, we must empty the input buffer:
  41.     // fflush(stdin);   // flushes the input buffer of a stream,
  42.                         // but gives undefined behavior. Alternative is:
  43.     // while ( ( getchar() ) != EOF && c != '\n' );
  44.     // or:
  45.     while ( ( getchar() ) != '\n' );
  46.  
  47.     printf("\n\n Enter your student roll number: ");
  48.     scanf("%d",&s1.roll_number);    // required &
  49.     printf("\n\n Student detailed are: \n");
  50.  
  51.     printf("\n name: %s \n\n roll number: %d \n\n", s1.name, s1.roll_number );
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement