-1

I am trying to get ALL tokens in a string using strtok() and convert them to integers. After getting one token, trying to pull another promptly segfaults - how do I tell the system that this is not a segfault condition so it can complete?

Code:

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;
  }

Is casting away const why it segfaults? If so how do I get around this?

4

2 回答 2

1

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;
}
于 2013-05-02T20:43:44.010 回答
1

我认为应该是

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;
    }
 }
于 2013-05-02T20:46:57.307 回答