如何检查char是否在.txt文件中?

时间:2014-02-28 02:34:29

标签: c

在我的程序中,我应该在C中进行高峰时间游戏。我正在导入从文本文件中显示的板。

之后我要求用户输入,这应该是他想要移动的棋盘上的字符。

我的问题是当用户选择char时,如何检查他选择的char是否存在于board.txt文件中,因为如果没有,我需要让用户选择一个新角色。

这是代码的输入部分到目前为止的样子:

char Direction[1];
char Vehicle[1];
int intInput =0;

// get the char input for the type of vehicle
printf("Please enter which vehicle you would like to move:\n");
scanf("%s", &Vehicle);
//THIS IS WHERE I NEED TO CHECK IF THE CHAR PICKED EXISTS IN board.txt 
printf(" This is the input: %s\n", Vehicle);

//get the char input for the direction you want to move
printf("Please choose if you want to move right(R) or left(L):\n");
scanf("%s", &Direction);

if(Direction != "r"||"l"){
    printf("Please choose a valid direction(R=Right L=Left):\n");
    scanf("%s", &Direction);
}
else{
    printf("Your move was %s\n", Direction);
}
//get the int input
printf("Enter how far you would like to move:");
scanf("%d", &intInput);

if(intInput<0){
    printf("Please enter a positive integer:");
    scanf("%d", &intInput);
}
else{
    printf("The inpuy is %d", intInput);
}

1 个答案:

答案 0 :(得分:0)

how I check if the char he picked exists in the board.txt

最好的方法是将每行数据读入缓冲区以使用fgets

在该缓冲区中找到char。要查找使用strchr

以下代码说明了我的意思

FILE *  fp;
fp= fopen("board.txt", "r");
char    buffer[256];

if (!fp)
{
    printf("error");
    return;
}
while (fgets(buffer, 256, fp))
{
   char *ptr = strchr(str, Direction);
    if(ptr)
       printf("found\n");   
    else
      printf("Not found\n");    
} 
fclose(fp);