나는이 바보 같은 문제가 C에서 strtok() 사용하여 발생했습니다. main
루틴 내 변경된 토큰을 참석하는 것으로 나타나지 않는 동일한 작동하는 동안 sub_routine
에서 제가 다르게 수행 한 것은 static
에 토큰 문자를 유지하는 것입니다.strtok() 후속 호출에서 새로운 토큰 값에 관한하지 않습니다
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void sub_routine()
{
char str[80] = "This is { some important } website";
char *val = NULL;
val = (char *)malloc(sizeof(char)*255);
strncpy(val, str, sizeof(str));
static char s = '{';
char *token;
/* get the first token */
token = strtok(val, &s);
/* walk through other tokens */
while(token != NULL)
{
printf(" %s\n", token);
s= '}';
token = strtok(NULL, &s);
}
}
int main()
{
char symbol='{';
char *string = NULL;
char *match = NULL;
char ref[255]="Do something here {Do it now}. What now?";
string = (char *)malloc(sizeof(char) * 255);
strncpy(string, ref, sizeof(ref));
match = strtok(string, &symbol);
printf("\n%s", match);
printf("\n%s", string);
if(string!= NULL)
{
symbol = '}';
match= strtok(NULL, &symbol);
printf("\n%s\n", match);
}
sub_routine();
}
누군가가 문제를 해결해 줄 수 있습니까?
왜 'strtok'을 사용하고 있습니까? 이것은 표준 라이브러리 중 최악의 기능 중 하나입니다. – CodesInChaos
구분 기호는 널로 끝나는 문자열로 지정해야합니다. 당신은 하나의 char에 포인터를 넘겨 주는데, 이것은 대부분 NULL로 끝나지 않는다. 's'를 배열로 만듭니다 :'char s [2] = "{";'. ('static' 변수는 0 바이트로 패딩되어 행동을 설명 할 수 있습니다.) –
@CodesInChaos 당신이 제안한 대안은 무엇입니까? (재진입 버전 제외)? – Anshul