嗨所以我写这段代码来查看一个文本文件并将它找到的每个单词放在一个c字符串数组中。我能够编写代码但是当实际文本文件中出现错误时我会遇到问题。例如,如果句子中有一个双重空格,我的程序会崩溃,例如"汽车快速行驶"它会停在车上。看着我的代码,我相信这是因为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语言但是我试图在c中充分利用它
答案 0 :(得分:0)
问题可能是您没有为空终止字符串分配足够的空间。
char *sentence = (char*) malloc(sizeof(char)*line.length());
strcpy(sentence,line.c_str());
如果你需要捕获"abc"
,你需要3个字符元素和另一个终止空字符,即总共4个字符。
malloc
的参数值需要增加1。
char *sentence = (char*) malloc(line.length()+1);
strcpy(sentence,line.c_str());
目前尚不清楚为什么在C ++程序中使用malloc
。我建议使用new
。
char *sentence = new char[line.length()+1];
strcpy(sentence,line.c_str());