0

strtok区切り文字を「,」と指定すると、スペースの後に文字列が分割されるのはなぜですか?

4

2 に答える 2

7

何が間違っているのかを正確に伝えるのは少し難しいですが、私はあなたが何か間違ったことをしていることを示唆することしかできません (詳細について尋ねるときは、通常、コードを投稿する必要があります)。次のようなサンプル プログラムは、問題なく動作するようです。

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

int main (void) {
    char *s;
    char str[] =
        "This is a string,"
        " with both spaces and commas,"
        " for testing.";
    printf ("[%s]\n", str);
    s = strtok (str, ",");
    while (s != NULL) {
        printf ("   [%s]\n", s);
        s = strtok (NULL, ",");
    }
    return 0;
}

以下を出力します。

[This is a string, with both spaces and commas, for testing.]
   [This is a string]
   [ with both spaces and commas]
   [ for testing.]

すぐに頭に浮かぶ唯一の可能性は、" ,"代わりに を使用している場合です","。その場合、次のようになります。

[This is a string, with both spaces and commas, for testing.]
   [This]
   [is]
   [a]
   [string]
   [with]
   [both]
   [spaces]
   [and]
   [commas]
   [for]
   [testing.]
于 2010-08-10T07:05:35.363 に答える
0

ありがとう!私は周りを見回して、ユーザーが入力した行全体を読み取らないscanfに問題があることを発見しました。私の strtok は正常に機能していたようですが、strtok の戻り値と一致させるために使用している値が間違っています。たとえば、私の strtok 関数は "Jeremy Whitfield,Ronny Whiffield" を受け取り、"Jeremy Whitfield" と "Ronny Whitfield" を返します。私のプログラムでは、scanf を使用してユーザー入力 > 「Ronny Whitfield」を取り込みますが、これは実際には「Ronny」のみを読み取ります。したがって、strtokではなくscanfに問題があります。仮想マシンを開くたびにスタックするため、今のところコードにアクセスできません。

于 2010-08-10T14:09:52.830 に答える