fork download
  1. #include <ctype.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. int main(void) {
  6. char buf[999];
  7. while (fgets(buf, sizeof buf, stdin)) { // read a string rather than scanf an integer
  8. buf[strcspn(buf, "\n")] = 0; // remove trailing newline
  9. char *p = buf;
  10. int invalidflag = (*p == 0);
  11. unsigned sum = 0;
  12. unsigned product = 1;
  13. while (*p) {
  14. if (isdigit((unsigned char)*p)) {
  15. sum += *p - '0';
  16. product *= *p - '0';
  17. } else {
  18. invalidflag = 1;
  19. break;
  20. }
  21. p++;
  22. }
  23. if (invalidflag) {
  24. printf("input = \"%s\" ==> INVALID INPUT\n", buf);
  25. } else {
  26. printf("input = \"%s\"; sum = %d; product = %d\n", buf, sum, product);
  27. }
  28. }
  29. return 0;
  30. }
Success #stdin #stdout 0s 9424KB
stdin
f6o7o8b9a0r
2019

42
3.14
foobar
-17
stdout
input = "f6o7o8b9a0r" ==> INVALID INPUT
input = "2019"; sum = 12; product = 0
input = "" ==> INVALID INPUT
input = "42"; sum = 6; product = 8
input = "3.14" ==> INVALID INPUT
input = "foobar" ==> INVALID INPUT
input = "-17" ==> INVALID INPUT