1

Traveling Knight問題の非常に単純なBFS検索を行っています。残念ながら、私の入力はうまくいかないことにしました。このコードでは、正しい結果が得られます。

char start[2], destination[2];
scanf("%s", start);                    // input string is "e2"
printf("%d %d\n", start[0], start[1]); // start[0] = 101, start[1] = 50 
                                          (in ASCII, 101 is 'e' and 50 is '2')    

私が使っているもの

scanf("%s", start);                    // input string is "e2"
scanf("%s", destination);              // input string is "e4"
printf("%d %d\n", start[0], start[1]); // start[0] = 0, start[1] = 50

また

scanf("%s %s", start, destination);    // input string is "e2 e4"
printf("%d %d\n", start[0], start[1]); // start[0] = 0, start[1] = 50

ただし、宛先配列ではこの種のエラーは発生しません。私は何か間違ったことをしましたか?これが間違いである場合、使用できる代替手段はありますか?

編集: 開始は、宛先と同様に char[2] として宣言されます。SSCCE

void main()
{
    char start[2], destination[2];
    scanf("%s", start);                    // input string is "e2"
    scanf("%s", destination);              // input string is "e4"
    printf("%d %d\n", start[0], start[1]); // start[0] = 101, start[1] = 50 
}
4

1 に答える 1

2

4つのこと。

  1. void main()標準ではありません。を返す必要がありますint
  2. char バッファーの大きさが十分ではありません。
  3. scanf()配列に入れる文字列の長さは、配列サイズよりも 1 少なくなるように制限してください。バッファが小さすぎることを示唆していたはずです。"%1s"うーん....
  4. scanf()結果に頼る前に、結果を検証してください。

そうは言っても、

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

int main()
{
    int res = EXIT_FAILURE;

    char start[3], destination[3];
    if (scanf("%2s", start) == 1 && 
        scanf("%2s", destination) == 1)
    {
        printf("%d %d\n", start[0], start[1]);
        res = EXIT_SUCCESS;
    }
    return res;
}
于 2013-10-09T01:02:19.953 に答える