无法将字符串数组等同起来

时间:2014-05-26 00:52:11

标签: c arrays

第一次使用C,它是在uni的作业。 必须制作一个简单的测验程序,该程序从文本文件中读取格式为:

Question
Number of choices
Choice 1
Choice 2
...
Actual Answer
Question
Number of choices
...

出于某种原因,无论我如何摆弄和使用变量,我都无法将两个字符数组,实际答案和键入的答案识别为相等。请告诉我在哪里搞砸了(可能是很多地方,考虑到这是我在C的第一次拍摄)提前感谢,这是我的代码。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* readnextln(FILE *stream);
void writenextln(FILE *stream);

int main(){
    char currentstring[512], answer[512], preanswer[512], playeranswer[512];
    int i, cor, tot, ansnum;

    printf("\nWelcome to the quiz program!\n");
    printf("Type 'Exit' at any time to quit!\n\n");

    FILE *fp = fopen("questions.txt", "r");

    do    {
        writenextln(fp); //Question
        ansnum=0;
        strcpy(currentstring,readnextln(fp)); //Read line
        if (feof(fp)==0){
            ansnum=atoi(currentstring); //If the file hasn't ended, this line is the number of answers.
            for (i=0;i<ansnum;i++){
                writenextln(fp); //Write that many next lines.
            }
            strcpy(preanswer,readnextln(fp)); //Store the next line as the answer
            strncpy(answer, preanswer, strlen(preanswer)-1); //Remove trailing newline character
            printf("\n");
            scanf("%s",playeranswer); //Get player's answer
            if (playeranswer=="exit"){
                printf("You scored %d/%d!",cor,tot);
                exit(0); //If rthey say exit, exit
                }
            else{
                    cor+=checkcorrect(playeranswer==answer,answer); //Otherwise, check correctness and do things accordingly
                    tot++;
            }
        }
    }
    while (feof(fp)==0);

    fclose(fp);

    printf("You scored %d/%d!",cor,tot);
    exit(0);
}

char* readnextln(FILE *stream){
    char tempstring[5000];
    fgets(tempstring,5000,stream);
    return tempstring;
}

void writenextln(FILE *stream){
    char tempstring[5000];
    fgets(tempstring,5000,stream);
    printf(tempstring);
}

int checkcorrect(int yes, char *ans){
    if (yes==1){
        printf("Correct!\n\n\n");
        return 1;
    }
    else{
        printf("Incorrect! The answer is %s!\n\n\n",ans);
        return 0;
    }
}

1 个答案:

答案 0 :(得分:3)

您需要比较指针值,而不是它们指向的值。如果它们包含的内存地址相同,则指针比较成立。要比较字符串相等性,请使用strcmpstrncmp

此外:

char* readnextln(FILE *stream){
    char tempstring[5000];
    fgets(tempstring,5000,stream);
    return tempstring;
}

这是未定义的行为(换句话说,最糟糕的非法行为)。您正在返回一个指向本地内存的指针,该数据可能会在下一个函数调用(任何函数调用)后被覆盖并填充垃圾。