-1

を使用して文字列内のすべてのトークンを取得し、strtok()それらを整数に変換しようとしています。1 つのトークンを取得した後、すぐに別のトークンを取得しようとすると segfault が発生します。これが segfault 状態ではないことをシステムに伝えて完了できるようにするにはどうすればよいですか?

コード:

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

なぜそれがセグメンテーション違反になるのですか?もしそうなら、どうすればこれを回避できますか?

4

2 に答える 2

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 に答える
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 に答える