if else statement double printing C -
i'm writing program adds line numbers c files. filenames command line arguments wanted user have chance enter them if forget when run program. ask user if want enter filenames , answer 'y' or 'n'. given 5 tries answer correctly if invalid character entered after 5 tries program prints error message , terminates. if user enters invalid character have print '[y/n]?' screen prompt user letters. if invalid character entered though goes through loop twice , prints them out side side. why happen?
compiler.c file:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "linenumadderheader.h" #include "miscellaneousheader.h" #include "errorcheckedfunctionsheader.h" int main(int argc, char *argv[]){ int = 1; char ch; int answertries = 0; char *seperatedfilenames[argc - 1]; if (argc < 2){ fprintf(stderr, "no files entered compiling.\n"); answer: do{ if (answertries == 0) printf("would enter files compiling [y/n]? "); else if (!(answertries < 5)) fatal("in main(). invalid character entered many times."); else printf("[y/n]? "); ch = getchar(); if (ch == 'n' || ch == 'n') exit(0); answertries++; } while (ch != 'y' && ch != 'y'); } else{ while (i < argc){ seperatedfilenames[i - 1] = argv[i]; i++; } } = 0; while (i < (argc - 1)){ linenumadder(seperatedfilenames[i]); i++; } }
fatal funciton:
/*displays fatal error*/ void fatal(char *errormessage){ /*holds errormessage*/ char completederrormessage[strlen(errormessage) + 17]; /*copies error message completederrormessage*/ strcpy(completederrormessage, "[!!] fatal error "); strcat(completederrormessage, errormessage); /*prints error message screen*/ fprintf(stderr, "%s\n", completederrormessage); /*exit program in failure*/ exit(-1); }
your getchar()
call returns 1 character standard input. when users enters answer, hits enter/return key translates new line character part of line sent standard input.
what should check first character returned getchar
, then, in loop, read , discard characters until new line character (\n
). then, can proceed ask question time.
you should use loop because user may enter several characters @ once. example may enter "yes" count 4 characters.
Comments
Post a Comment