【发布时间】:2012-01-10 06:57:20
【问题描述】:
谁能告诉我这段代码有什么问题?
for(int i=0;i<4;i++)
{
long int a = strtol(strtok("1-2-3-4","-"),(char**)NULL,10);
cout << a <<endl
}
我在 Solaris Unix 上运行。它给了我一个分段错误。
故障在strtol()。
【问题讨论】:
谁能告诉我这段代码有什么问题?
for(int i=0;i<4;i++)
{
long int a = strtol(strtok("1-2-3-4","-"),(char**)NULL,10);
cout << a <<endl
}
我在 Solaris Unix 上运行。它给了我一个分段错误。
故障在strtol()。
【问题讨论】:
错误在于strtok 调用,而不是strtol。您不能在字符串文字上调用 strtok,因为它会尝试修改字符串。修改字符串文字会导致 C++ 中出现未定义的行为。
【讨论】:
问题很多。
我希望核心转储是因为字符串"1-2-3-4" 存储在只读内存中,所以当strtok() 修改它(以隔离第一个令牌)时,程序崩溃。你说崩溃在strtol();这表明 strtok() 的返回值为 NULL。
第一次调用strtok() 使用字符串作为参数;第二个调用在其位置传递 NULL 以指示“从上次中断的地方继续”。如所写,如果字符串是可修改的,那么您将解析 1 四次。
这更接近正确(尽管未经测试):
char input[] = "1-2-3-4";
char *data = input;
for (int i = 0; i < 4; i++)
{
char *token = strtok(data, "-");
if (token != 0)
{
long int a = strtol(token, NULL, 10);
cout << a << endl;
}
data = NULL;
}
一般情况下,需要从strtol()做错误检测;此外,这样做非常令人担忧。但是,使用示例字符串,您不必担心。
【讨论】:
由于这个问题已经讨论过了,我想展示另一种方法:
#include <stdio.h>
#include <string.h>
int main ()
{
long int a;
char str[] ="1-2-3-4";
char * pch;
pch = strtok (str,"-");
while (pch != NULL)
{
a = strtol(pch,(char**)NULL,10);
cout << a <<endl;
pch = strtok (NULL, "-");
}
return 0;
}
【讨论】: