fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. char* strdup(const char *str)
  6. {
  7. int len = strlen(str);
  8. char *str2 = malloc((len + 1) * sizeof (char));
  9. if (str2) strcpy(str2, str);
  10. return str2;
  11. }
  12.  
  13. int main()
  14. {
  15. FILE *f = stdin;
  16. /** @todo evaluation of command line arguments could override f with fopen(). */
  17. /* read input */
  18. if (!f) {
  19. fprintf(stderr, "ERROR: Cannot read input!\n");
  20. return 1;
  21. }
  22. int nGates = 0, nVars = 0;
  23. char **vars = NULL;
  24. char buffer[80];
  25. for (int iLine = 1; fgets(buffer, sizeof buffer, f); ++iLine) {
  26. char *op = strtok(buffer, " \t\r\n");
  27. if (!op
  28. || strcmp(op, "AND") != 0 && strcmp(op, "OR") != 0 && strcmp(op, "XOR") != 0
  29. && strcmp(op, "NAND") != 0 && strcmp(op, "NOR") != 0) {
  30. fprintf(stderr, "ERROR in line %d: OP expected!\n", iLine);
  31. continue;
  32. }
  33. char *var;
  34. while (var = strtok(NULL, " \t\r\n")) {
  35. if (var[0] == 't') {
  36. int found = 0;
  37. for (int i = 0; i < nVars; ++i) {
  38. if (found = (strcmp(var, vars[i]) == 0)) break;
  39. }
  40. if (found) continue; /* continues the while (var = strtok(NULL, " \t\r\n")) loop */
  41. ++nVars;
  42. vars = realloc(vars, sizeof (char*) * nVars);
  43. if (!vars) {
  44. fprintf(stderr, "ERROR: Out of memory!\n");
  45. return 1;
  46. }
  47. int iVar = nVars - 1;
  48. vars[iVar] = strdup(var);
  49. printf("Var. #%d: '%s'\n", iVar, var);
  50. }
  51. }
  52. ++nGates;
  53. }
  54. /* evaluate input */
  55. printf("Report:\n");
  56. printf("nGates: %d, nVars: %d\n", nGates, nVars);
  57. for (int i = 0; i < nVars; ++i) {
  58. printf("vars[%d]: '%s'\n", i, vars[i]);
  59. }
  60. /* clean-up */
  61. for (int i = 0; i < nVars; ++i) free(vars[i]);
  62. free(vars);
  63. /* done */
  64. return 0;
  65. }
Success #stdin #stdout 0s 4536KB
stdin
OR IN1 IN2 temp1
OR IN3 IN4 temp2
OR IN5 IN6 temp3
OR IN7 IN8 temp4
AND temp1 temp2 temp5
AND temp3 temp4 temp6
XOR temp2 temp6 OUT1
stdout
Var. #0: 'temp1'
Var. #1: 'temp2'
Var. #2: 'temp3'
Var. #3: 'temp4'
Var. #4: 'temp5'
Var. #5: 'temp6'
Report:
nGates: 7, nVars: 6
vars[0]: 'temp1'
vars[1]: 'temp2'
vars[2]: 'temp3'
vars[3]: 'temp4'
vars[4]: 'temp5'
vars[5]: 'temp6'