Advertisement
Guest User

Untitled

a guest
Sep 30th, 2016
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. //moved the fixed sizes to defines and have 2. 1 for the main buffer, and one for the name fields
  5. #define maxinput 256
  6. #define maxname 16
  7.  
  8. int main()
  9. {
  10. char input[maxinput];//large buffer to accept more input than name fields allow - note that too can overflow as the value is fixed
  11. char firstname[maxname];
  12. char lastname[maxname];
  13. char caniexit; //character switch variable
  14. int temp_length, lc; //integers - store strlen result in a variable to avoid recalculating each time, loop counter
  15.  
  16. caniexit = 'n'; //initiallise switch to n
  17. while (caniexit == 'n') //start while loop to loop until caniexit is not n
  18. {
  19. printf("Type your first name: ");
  20. fgets(input,maxinput,stdin);
  21. temp_length = strlen(input);
  22. if ( input[temp_length-1] == '\n')
  23. input[temp_length-1] = '\0';
  24. temp_length = strlen(input);//if the new line was replaced, the string length is now different
  25. if (temp_length >= maxname)//check for correct length
  26. printf("Error: name too long, enter 15 or fewer characters.\n");
  27. else
  28. caniexit = 'y';//if length ok, set switch to y in order to allow loop exit
  29. }
  30. //Left behind after adding above loop to ensure name fits, but this bit limits the number of characters to transfer to the name variable to 15
  31. if ( temp_length >= maxname)
  32. temp_length = maxname-1;
  33. //start for loop - type of while for counting sequentially through a range of numbers and acting on each value.
  34. // first part start the loop counter at zero; next while the counter is less than the length of the string; increment counter after each run of the loop
  35. for (lc=0; lc < temp_length; lc++)
  36. firstname[lc] = input[lc];
  37. firstname[lc] = '\0';
  38.  
  39. caniexit = 'n';
  40. while (caniexit == 'n')
  41. {
  42. printf("Okay, %s, now tell me your last name: ",firstname);
  43. fgets(input,maxinput,stdin);
  44. temp_length = strlen(input);
  45. if ( input[temp_length-1] == '\n')
  46. input[temp_length-1] = '\0';
  47. temp_length = strlen(input);
  48. if (temp_length >= maxname)
  49. printf("Error: name too long, enter 15 or fewer characters.\n");
  50. else
  51. caniexit = 'y';
  52. }
  53. if ( temp_length >= maxname)
  54. temp_length = maxname-1;
  55. for (lc=0; lc < temp_length; lc++)
  56. lastname[lc] = input[lc];
  57. lastname[lc] = '\0';
  58. printf("Pleased to meet you, %s %s.\n",firstname,lastname);
  59.  
  60. return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement