简体   繁体   中英

Why does fputc() skips every other character

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;
}

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') { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM