cs1713-day1-prog3.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (C) 2020, 2019, 2018, 2017 Girish M
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program; if not, write to the Free Software
  15. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  16. * MA 02110-1301, USA.
  17. *
  18. */
  19. /*----------------------------------
  20. Name: Girish M
  21. Roll number: cs1713
  22. Date: 25 July 2017
  23. Program description: Sum of n integers
  24. Acknowledgements:http://pubs.opengroup.org/onlinepubs/7908799/xsh/regcomp.html
  25. ------------------------------------*/
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <regex.h>
  29. int match(const char *string, char *pattern)
  30. {
  31. int status;
  32. regex_t re;
  33. if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {
  34. return(0); /* report error */
  35. }
  36. status = regexec(&re, string, (size_t) 0, NULL, 0);
  37. regfree(&re);
  38. if (status != 0) {
  39. return(0); /* report error */
  40. }
  41. return(1);
  42. }
  43. int main(int argc, char* argv[])
  44. {
  45. int i, sum=0;
  46. char* pattern = "^[+-]?[0-9]+$";
  47. if(argc > 1)
  48. {
  49. for(i=1; i<argc; i++)
  50. {
  51. if(match(argv[i], pattern))
  52. sum = sum + atoi(argv[i]);
  53. else
  54. printf("\n%s is not an integer. Excluding in sum.\n", argv[i]);
  55. }
  56. printf("\nSum is %d\n", sum);
  57. }
  58. else
  59. {
  60. printf("\nUsage: ./cs1713-day1-prog3.o int1 int2 ...\n");
  61. }
  62. return 0;
  63. }