所以我要做的是创建一个c ++函数,该函数读取一个文件并将该文件的文本转换为标记向量。
现在我拥有的文本文件需要许多分隔符,包括句点、引号等。所以我认为 strtok 会比 sstream 更好地读取令牌。但是,当遍历我的向量时,我注意到其中没有任何内容。代码出现空白。我究竟做错了什么?
请帮我!
我的代码在这里:
void getTokenFreq(string inFile_name) {
ifstream inFile;
int n = 0;
char *token;
vector<string> result(1);
inFile.open(inFile_name);
if (inFile.fail()){
cout << "Fail to open the file tmp.txt.\n";
exit(-1);
}
while(inFile.good()) {
getline(inFile, s);
char *str = new char[s.length() + 1];
strcpy(str, s.c_str());
token = strtok(str, " ’—\",;.:?“”");
while (token != NULL) {
result.push_back();
token = strtok (NULL, " ’—\",;.:?“”");
n++;
}
}
for(int i = 0; i < n; i++) {
cout << result[i];
}
inFile.close();
}
您不错,但有一些错误:
第一的:
vector<string> result(1);
为什么一std::string
开始会有一个空的?这会破坏你的载体,其结果会是这样:"", "one", "two", "three", ...
。更改为:
vector<string> result;
第二:
result.push_back();
你不能不push_back
带参数地调用。根据您的程序逻辑,您应该push_back
将token
,因此将其更改为:
result.push_back(token);
第三:
您不会释放分配的内存。在内部一段时间后,调用:
delete [] str;
另外std::string s
是不是在你的函数可见,但我相信它是全球性的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句