c - Trying to randomly generate a string in order to get a conditional to execute -
seems strings in c weak point, need guys' again. should have included in first one, apologize that.
so have function got working correctly, fills string random chars set {r, e, s, e, t} , returns it:
char *inputstring() { static char string[6]; const char *digits = "reset"; int i; (i = 0; < 5; i++) { string[i] = digits[ rand() % 4 + 0 ]; } return string; }
so char @ string[5] '\0', correct? , string[1] through string[4] random combinations of other characters (r, e, s, e, t).
now, have function calls one. these purpose of trying printf statement execute:
other_fxn() { char *s; while (1) { s = inputstring(); if (s[0] == 'r'&& s[1] == 'e' && s[2] == 's' && s[3] == 'e' && s[4] == 's' && s[5] == '\0') { printf('worked!\n'); break; } } }
main:
{ srand(time(null)); other_fxn(); }
it compiles fine loop runs forever, if statement never executing. can me out why won't execute. once again.
while (1) { s = inputstring(); if (s[0] == 'r'&& s[1] == 'e' && s[2] == 's' && s[3] == 'e' && s[4] == 't' && s[5] == '\0') { printf('worked!\n'); break; } }
first of all, in example looking word "reses". , don't change string inside loop. out of loop if random string reset after initial generation. don't know why need this, code above out of loop. maybe not soon, will.
also, one:
string[i] = digits[ rand() % 4 + 0 ];
why + 0?
, why % 4
, not % 5
?
better go this:
char *inputstring() { static char string[6]; const char *digits = "reset"; (int = 0; < 5; i++) { string[i] = digits[ rand() % 5]; } return string; }
and try using debugger, helps.
Comments
Post a Comment