【发布时间】:2017-02-22 23:35:07
【问题描述】:
所以我想做的是创建一个 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();
}
【问题讨论】:
-
“代码出现空白”。你什么意思?这里有一些错误,所以它甚至不应该编译。
-
result.push_back(); [原文如此],试试 result.emplace_back(token);
-
能否请您发布一个可以按原样编译的完整示例程序?会更容易帮助...
-
while(inFile.good()) {这一切都很好,但是您真正想知道的是getline(inFile, s);之后的流状态。while(getline(inFile, s)) {为您提供两全其美的体验。更多细节在这里:stackoverflow.com/questions/5605125/…