字符串::std find 方法始终查找字符,即使它不在字符串中
string::std find method always find a character, even when it's not in the string
我正在为学校做一个项目,我们正在解析从文本文件传入的字符串。然而,我有问题与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))
...
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 按类型与字符串查找对象
- 使用C RTTI(内置)通过字符串查找功能指针
- 关于获取行和字符串查找函数的问题
- 字符串查找方法找不到第一字母
- C++ 字符串.查找()
- 遇到字符串::查找的问题
- 将一个数组作为子字符串查找到另一个数组中
- 字符串查找第一个非的 C++ 问题
- 如何将通配符与字符串::查找一起使用
- 字符串::查找问题 (C++)
- 性能标准::strstr vs. 标准::字符串::查找
- C++字符串::查找崩溃应用程序
- 使用字符串查找单词的正确方法是什么
- 如何在<string>没有 std::string 中介的情况下制作一个支持通过 C 字符串查找的集合?
- 使用C++根据行中的第一个字符串查找行(仅一个)
- Borland字符串::查找bug
- std::map如何通过字符串查找元素
- 字符串查找函数返回奇数
- 如何使用子字符串查找数字行的正确部分