-1

I'm trying to compare if user input is the same as in text file. in printf("U = %s, R = %s.", uAts, rline);line i get that a = a, but it still goes to else statement. Maybe there is like some other method for comparing strings in C language which I don't know?

void nextQ(int klL, FILE *kl, FILE *ats, FILE *atsR){
    int i, uAts[500], at;
    char kline[500], aline[500], rline[500], b[1];
    system("cls");

    for (i = 0; i <= klL; i++){
        fgets(kline, 500, kl);
        fgets(aline, 500, ats);
        fgets(rline, 500, atsR);
 }
    printf("%s\n", kline);
    printf("%s\n\n", aline);
    printf(rline);

    printf("Jusu atsakymas: ");
    scanf("%s", &uAts);
    printf("U = %s, R = %s.", uAts, rline);
        if(uAts == rline){
            printf("Klausimas atsakytas teisingai!\n");
            printf("Noredami pereiti prie kito klausimo iveskite bet koki simboli ");
            scanf("%s", b);     
            nextQ(klL+1, kl, ats, atsR);        
        }else{
            printf("Neteisingai\n");
        }
}


int main(int argc, char *argv[]) {
    int pas, klL = 0;
    char term;
    bool menu = true;

    //textiniu failu nuskaitimas
    FILE *kl;
    kl = fopen("Klausimai.txt", "r");
    FILE *ats;
    ats = fopen("Atsakymai.txt", "r");
    FILE *laim;
    laim = fopen("Laimejimas.txt", "r");
    FILE *atsR;
    atsR = fopen("AtsR.txt", "r");

    do{
        //menu
        printf("1. Pradeti zaidima.\n");
        printf("2. Iseiti\n");
        printf("Jusu pasirinkimas: ");
        scanf("%d%c", &pas, &term);

        if(pas < 1 || pas > 2 || term != '\n'){
            printf("\nBloga ivestis");
            break;
        }else{
        nextQ(klL, kl, ats, atsR);
        }
    }while(menu);

    return 0;
}
Tadas
  • 95
  • 10
  • `scanf("%s", &uAts);` will invoke *undefined behavior* by passing pointer to object having wrong type to `scanf`: `%s` calls for `char*`, but you passed `char(*)[500]` – MikeCAT Jun 07 '16 at 16:33
  • using `scanf("%s", b);` with `char b[1];` is also bad because considering the terminating null-character, it can only read zero character without causing out-of-range access, which invokes *undefined behavior*. – MikeCAT Jun 07 '16 at 16:34
  • `printf(rline);` is another bad thing because it will invoke *undefined behavior* for luck of data if user input something like `%s%s%s%s%s%s%s%s%s%s` – MikeCAT Jun 07 '16 at 16:35
  • Also don't forget to remove the newline character read via `fgets()` to do proper comparision. – MikeCAT Jun 07 '16 at 16:36

1 Answers1

5

Besides the issues mentioned in the comments: you can't compare strings like that:

if(uAts == rline) 

That wil compare the addresses of the char arrays and these will always be different. Use

if( strcmp( uAts, rline ) == 0 )

instead. strcmp() will compare the contents of two NUL terminated char arrays (aka "strings" in C).

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33