字符串::std find 方法始终查找字符,即使它不在字符串中

string::std find method always find a character, even when it's not in the string

本文关键字:字符串 查找 find std 方法 字符      更新时间:2023-10-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("|")不起作用吗?

*编辑添加如何从文件

获取字符串

您可能需要查看一些文档,以便了解std::string::find返回值的实际含义。特别是,如果您不确定某个值是否存在,则应该在使用它之前将其与npos进行比较,而不是"-1"。在你的输入耗尽后,它继续运行的问题可能最好在你没有显示的输入代码中解决,而不是试图解析一些可能是或可能不是实际输入的string

更新:正如我在下面对vsoftco的评论中推测的那样,你的输入逻辑被打破了。使用:

while (getline(inFile, theFile))
    ...