c - Searching char array for char -
i have been attempting iterate through predetermined array of characters , compare scanned in single char. if scanned char in array want add 2d array if isn't in array want error handling.
my code currently
char c; char legalchar[] = "./\\=@abcdefghijklmnopqrstuvwxyz\n"; int rowcount = 0; int colcount = 0; int = 0; file * map; while (c = fgetc(map), c != eof) { while (i < (sizeof(legalchar))){ if (c == legalchar[i]){ if (c == '\n'){ /*add 1 number of rows , start counting columns again */ rowcount++; colcount = 0; } else { /*would have code add char 2d array here */ colcount++; } } i++; }
i planned have
if (c != legalchar[i]){ /*error handling */ }
but doesn't work because jumps if statement on every iteration.
the output program @ moment colcount gets assigned 1 , rowcount stays @ 0. chars iterated through inside of legalchar[] array i'm not sure i'm doing wrong.
any advice appreciated.
thanks
your problem if (c != legalchar[i])
true. character entered m
, in legalchar
. if check c != legalchar[i]
, you're checking c != '.'
first time, true.
the better way handle having flag value starts false , set true if find something. once finish loop, if flag still false, know value wasn't found.
additionally, should reset i
each time go through loop, , for
loop makes more sense while
loop, if you're using c99
, i
can declared within loop..
int c; char legalchar[] = "./\\=@abcdefghijklmnopqrstuvwxyz\n"; int rowcount = 0; int colcount = 0; int = 0; int found = 0; file * map; while (c = fgetc(map), c != eof) { found = 0; (i = 0; < sizeof(legalchar); i++){ if (c == legalchar[i]){ if (c == '\n'){ /*add 1 number of rows , start counting columns again */ rowcount++; colcount = 0; } else { /*would have code add char 2d array here */ colcount++; } found = 1; // break out of loop here? } } if (!found) { // error handling here } }
Comments
Post a Comment