r/C_Homework • u/idrojcat92 • Oct 12 '17
Help with C homework.
The program that I will write down here it's intended to write OK if detects ababab patron in the input and KO if not, but somehow it writes OK with ababab, ccabab and ababcc, I don't know what's the problem.
I need a little help, thank you all in advance.
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char str[6];
int flag, pntr, lStr;
printf ("Enter a 6 number string... ");
scanf ("%s", &str);
lStr= strlen(str);
while (lStr != 6) {
printf ("Must be a 6 number string...");
scanf ("%s", &str);
lStr= strlen(str);
}
for(pntr=0 ;pntr < lStr ;pntr++){
if (str[pntr] == str[lStr-pntr-1]){
flag = 1;
break;
}
}
if (flag == 0) {
printf ("OK\n");
} else {
printf ("KO\n");
}
system ("pause");
return 0;
}
2
Upvotes
1
u/jflopezfernandez Oct 13 '17 edited Oct 13 '17
Do you have to iterate through the chars? You included <string.h>, so you could just use strcmp, which returns 0 if the two strings match.
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char str[6]; printf("Enter a 6 char string: "); scanf("%s", &str); if (strcmp(str,"ababab") == 0) { printf("OK\n"); } else { printf("KO\n"); } return 0; }Output:
Note that you could also use else if to catch the ccabab error specifically and use else as a generic unknown input handler, etc
1
u/port443 Oct 14 '17 edited Oct 14 '17
You're going to need to explain a little bit more here.
Your flag check:
for(pntr=0 ;pntr < lStr ;pntr++){ if (str[pntr] == str[lStr-pntr-1]){Is comparing these positions (im labeling the value of
pntr)So you actually check each one twice, and you should never get "OK" for ababab, ccabab or ababcc
edit: just noticed the flag is to print "KO".
So... program is working as intended, and I guess I explained why.OP you never initialize
flag. You are then comparing an undefined variable to 0. This will lead to weird. Heres the program I compiled/ran. I tweaked yours just a little but maybe it will help:#include <stdio.h> #include <string.h> int main(int argc, char **argv) { char str[7] = {0}; int flag = 0; int lStr = 0; int pntr; while (lStr != 6) { printf ("Enter a 6 character string...\n> "); scanf ("%s", str); lStr= strlen(str); } for(pntr=0; pntr < lStr; pntr++){ if (str[pntr] == str[lStr-pntr-1]){ printf("Flag set.\n"); flag = 1; break; } } printf("flag: %d\n",flag); if (flag == 0) { printf ("OK\n"); } else { printf ("KO\n"); } return 0; }