编译器在 strstok() 之后不继续 (C++)

Compiler doesn't proceed after strstok() (C++)

本文关键字:继续 C++ 之后 编译器 strstok      更新时间:2023-10-16

我使用了带有while循环的strtok()函数并对其进行了编译,但while循环之后的ANYTHING似乎对编译器不存在:

int main()
{
    int j = 1;
    char a[60] = "ion ana adonia doina doinn ddan ddao . some other words ";
    char *pch[36];
    pch[0] = strtok(a, ".");
    while (pch[j + 1] != NULL)
    {
        cout << pch[j - 1] << endl;
        pch[j] = strtok(NULL, ".");
        j++;
    }
    cout << "hello!"; //this doesnt display at all
        return 0;
}

我正在使用c-free。

除其他外,while循环结束条件是错误的。您正在检查pch[j + 1],它总是未初始化的内存,导致循环不可预测地继续,直到您在内存中遇到零,这可能会导致循环停止。

另一方面,我强烈反对在C++中使用strtok,因为它会破坏字符串。Boost有一个非常好的字符串解析功能,即使在基本的C++语言中,它也足够简单,可以使用内置的字符串功能进行大多数解析。

您的代码很奇怪。试试这个:

int main()
{
    int j = 0;
    char a[60] = "ion ana adonia doina doinn ddan ddao . some other words ";
    char *pch[36];
    pch[j] = strtok(a, ".");
    while (pch[j] != NULL)
    {
        cout << pch[j] << endl;
        pch[++j] = strtok(NULL, ".");
    }
    cout << "hello!"; //this doesnt display at all
    return 0;
}