2016-04-05 8 views
0

こんにちは、このコードを書いて、テキストファイルを調べて、Cの文字列配列にある各単語を配置します。コードを書くことができましたが、実際のテキストファイルに間違いがあると問題が発生します。私のプログラムは、 "車が速く行く"のような文章に二重のスペースがあるとクラッシュするでしょう。それは車で止まるでしょう。私のコードを見て、私はこれがstrtokのためだと信じています。私は、次の値のトークンを作るstrtokは確認する必要があり、問題を解決すると思いますが、私が何をどのように確認していないので、strtokコンパイラエラーを修正するには?

私のコード

#include <iostream> 
#include <fstream> 
#include <string.h> 
#include <stdlib.h> 
using namespace std; 

int main() { 
    ifstream file; 
    file.open("text.txt"); 
    string line; 

    char * wordList[10000]; 
    int x=0; 

    while (getline(file,line)){ 

     // initialize a sentence 
     char *sentence = (char*) malloc(sizeof(char)*line.length()); 
     strcpy(sentence,line.c_str()); 

     // intialize a pointer 
    char* word; 

     // this gives us a pointer to the first instance of a space, comma, etc., 
     // that is, the characters in "sentence" will be read into "word" 
     // until it reaches one of the token characters (space, comma, etc.) 
    word = strtok(sentence, " ,!;:.?"); 

     // now we can utilize a while loop, so every time the sentence comes to a new 
     // token character, it stops, and "word" will equal the characters from the last 
     // token character to the new character, giving you each word in the sentence 

     while (NULL != word){ 
     wordList[x]=word; 
     printf("%s\n", wordList[x]); 
     x++; 
     word = strtok(NULL," ,!;:.?"); 
     } 
    } 
    printf("done"); 
    return 0; 
} 

私は++のコードの一部はCである知っているし、いくつかはcですが、私はそれを最大限に活用しようとしています

答えて

0

ヌルで終了する文字列に十分なスペースを割り当てていない可能性があります。

char *sentence = (char*) malloc(sizeof(char)*line.length()); 
    strcpy(sentence,line.c_str()); 

あなたが​​をキャプチャする必要がある場合は、3つの文字の要素と終端のNULL文字、すなわち4つの文字の合計のための別のものを必要とします。

あなたがC++プログラムでmallocを使用している理由は明らかではない。1.

char *sentence = (char*) malloc(line.length()+1); 
    strcpy(sentence,line.c_str()); 

によって増加するmallocニーズへの引数の値。私はnewの使用をお勧めします。

char *sentence = new char[line.length()+1]; 
    strcpy(sentence,line.c_str()); 
+1

教授は、C++とcとを組み合わせていますが、cクラスであるはずです。だから私は本当に今はC++についてはあまりよくありません。 – alex

+0

@alex、あなたの教授があなたが使っているものに気をつけなければ、可能な限り多くのことに固執してください。 –

+0

は、私は実際に読むことを想定されたファイルをテストし、問題が値それは、ダブルスペースのような連続した順序でヌル尻に回すことになったり二つの言葉は、それらの間でのみの期間を持っているときには、故障しているです。 – alex

関連する問題