2014-02-28 41 views
0

在我的程序中,我應該用C語言進行高峯時間的遊戲。我正在導入從文本文件中顯示的棋盤。如何檢查char是否在.txt文件中?

之後,我問用戶輸入,這應該是他想要移動的董事會上的字符。

我的問題是當用戶選擇字符時,我如何檢查他選擇的字符是否存在於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); 
} 
+5

您需要閱讀教科書/場/不管再'方向!=「R」 ||「升」'沒有做什麼你認爲它確實...問題的答案是當你閱讀board.txt時,你需要「記住」它裏面的內容,以便稍後使用它... – John3136

+1

如果事先知道板的大小,那麼你可以將它存儲在一個緩衝區中(如果你想多次操作同一塊電路板,那麼最好將它保存在緩衝區中,而不是多次讀取文件)。然後在該緩衝區中搜索適當的字符,除了前面的註釋之外,還可以將if語句轉換爲while循環。 – bb94

+1

您如何儲存導入的電路板信息? –

回答

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);