【发布时间】:2015-05-15 03:53:16
【问题描述】:
我正在为学校做一个项目,我们正在解析从文本文件传入的字符串。但是,我遇到了 string.find 的问题。当我运行这段代码时:
string theFile;
while (inFile)
{
inFile.getline(line, 512);
theFile = line;
bool parsing = true;
while (parsing){
Choice *newChoice = new Choice;
if (theFile.find("|")!= -1) {
newChoice->lines = theFile.substr(theFile.find("%") + 1, theFile.find("|") - 1);
theFile.erase(0, theFile.find("|") + 2);
tempNPC->choices.push_back(newChoice);
}
else
parsing = false;
输入看起来像这样:
| d1% stuff | d2% more stuff |
我的问题:if 语句永远不会是假的。即使 theFile 为空,它仍会运行代码,因此出现越界错误。知道为什么 find("|") 不起作用吗?
*编辑添加我如何从文件中获取字符串
【问题讨论】:
-
theFile是什么类型? -
只是一个.txt文件
-
.txt 不是类型。您需要在代码中显示
theFile的声明,而不是假设每个人都知道您使用的类型。 -
哦,我误解了你在问什么。它是一个字符串。
string theFile; while (inFile) { inFile.getline(line, 512); theFile = line; -
你的内循环也很可怕,应该是
while( theFile.find('|') != string::npos )。正如您所拥有的那样,它既不必要地冗长,又会在最后一次迭代中泄漏内存。
标签: c++ string pointers visual-c++ string-parsing