[英]Why does this use of strtok() cause segmentation fault?
我正在尝试使用strtok()
在字符串中获取所有令牌并将其转换为整数。 获得一个令牌后,尝试立即拉出另一个段错误-如何告诉系统这不是段错误条件,以便可以完成?
码:
char * token;
while ( getline (file,line) )
{
char * charstarline = const_cast<char*>(line.c_str()); //cast to charstar
char * token;
token = strtok(charstarline," ");
token = strtok(charstarline," ");
int inttoken = atoi(token);
cout << "Int token: " << inttoken << endl;
while (token != NULL)
{
token = strtok (NULL, " ");
int inttoken = atoi(token);
cout << "Int token (loop): " << inttoken << endl;
}
抛弃const为什么会出现段错误? 如果是这样,我该如何解决?
除了const
讨论之外,这可能是您真正的问题;
while (token != NULL) // Up to the last token, is not NULL
{
token = strtok (NULL, " "); // No more tokens makes it go NULL here
int inttoken = atoi(token); // and we use the NULL right away *boom*
// before checking the pointer.
cout << "Int token (loop): " << inttoken << endl;
}
我认为应该
char * charstarline = malloc(sizeof(char)+1 * line.c_str() )
因为它将分配新的空间。
但,
char * charstarline = const_cast<char*>(line.c_str());
,将不会分配新空间。
通过执行以下示例,我得出了这个结论。
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main(){
char charstarline[] = "hello abc def how\0"; //cast to charstar
//here char * charstarline = "hello abc def how\0" is not working!!!!!
char * token;
token = strtok(charstarline," ");
//int inttoken = atoi(token);
//cout << "Int token: " << inttoken << endl;
while (token != NULL)
{
token = strtok (NULL, " ");
//int inttoken = atoi(token);
cout << "Int token (loop): " << token << endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.