1

I have a small program in C which starts with a menu which is implemented inside a function with a do{switch{case 1....}while loop

When case 1 validates it calls another function where a while loop takes getchar() values and write them into a file using fputc(). The problem is that it skips every other character.

Is there a trick around it?

So that my do{} while menu with its switch case can coexist with an isolated function that hosts my while loop and it's fputc() method?

Here a simplified version of the code.....

#include<stdio.h>
#include<stdlib.h>

int menu();
int v1();

int main(void) {
  menu();
  return 0;
}

int menu() {
  int opt;
  do {
    printf("\t 1] v1 \n");
    switch (opt) {
      case 1:
        v1();
    }
    scanf("%i", &opt);
  } while (opt != 100);
  return 0;
}

int v1() {
  FILE *fd;
  char target[10] = "v1.json";
  fd = fopen(target, "at");
  if (fd == NULL) {
    printf("Error");
  }
  int c;
  while ((c = getchar()) != EOF && (c = getchar()) != '\n') {
    fputc(c, fd);
  }
  fclose(fd);
  return 0;
}
dbc
  • 104,963
  • 20
  • 228
  • 340

1 Answers1

3

In the line

while ((c = getchar()) != EOF && (c = getchar()) != '\n') { ... }

you're reading in two characters from stdin, not one--because you're calling getchar() twice.

In order to fix that, since you already assigned the read char to the variable c, just use the variable in the second comparison, rather than calling the function once more:

while ((c = getchar()) != EOF && c != '\n') { ... }
sleighty
  • 895
  • 9
  • 29