首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >字符串操作方法产生RunTime错误

字符串操作方法产生RunTime错误
EN

Stack Overflow用户
提问于 2010-10-11 21:16:02
回答 3查看 168关注 0票数 0

这似乎给我带来了一点麻烦。此方法应生成一个随机数并将其分配给一个char。getline从文本文件中获取整个字符串,并将其分配给食品。Y的目的是保持它在食品字符串中找到c的位置。然后,它将使用int从字符串中擦除,并打印出剩下部分。

我一直收到"Program has requested to shutdown up an runtime error in a unusual“的提示,然后它就被锁住了。提前谢谢。

代码语言:javascript
运行
复制
   void feedRandomFood()
   {
       int y = 0;
       int x = rand() % food.size() + 1; //assigns x a random number between 1 and food.size MAX
       char c = '0' + x; //converts int to char for delimiter char.
       ifstream inFile;
       inFile.open("OatmealFood.txt", ios::in);
       string foods = "";
       getline(inFile, foods); 
       inFile.close();
       y = foods.find(c); 
       foods.erase(y); //erase characters up to the char found 
       cout << foods;
   }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-10-11 21:18:43

尝试:

请注意,foods.erase(y)将擦除'f‘前面的字符。如果您想要擦除'f‘以下的字符,请参阅此示例:

下面是一个简单的擦除字符的例子:

代码语言:javascript
运行
复制
  string x = "abcdefghijk";
  // find the first occurrence of 'f' in the string
  int loc = x.find('f');

  // erase all the characters up to and including the f
  while(loc >= 0) {
    x.erase(x.begin()+loc);
    --loc;
  }
  cout<<x<<endl;

程序输出:

代码语言:javascript
运行
复制
---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
ghijk

> Terminated with exit code 0.

因此,对于您的示例,您需要类似以下内容:

代码语言:javascript
运行
复制
while(y >= 0) {
    foods.erase(foods.begin() + y);
    --y;
}

while编辑您还可以消除while循环,只需调用重载的erase,如下所示:

代码语言:javascript
运行
复制
  string x = "abcdefghijk";
  int loc = x.find('f');
  if (loc >= 0) {
    x.erase(x.begin(),x.begin()+loc+1);
    cout<<x<<endl;
  }

程序输出:

代码语言:javascript
运行
复制
---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
ghijk

> Terminated with exit code 0.
票数 0
EN

Stack Overflow用户

发布于 2010-10-11 21:22:38

如果find方法在字符串foods中找不到c怎么办?它返回npos,当你在erase中使用它时,你的程序失败了。

因此,您需要在执行erase之前添加此检查

代码语言:javascript
运行
复制
y = foods.find(c);
if( y != string::npos) {
    foods.erase(y); 
}

此外,在您尝试从文件open中读取一行之前,您应该始终确保该文件成功。

代码语言:javascript
运行
复制
inFile.open("OatmealFood.txt", ios::in);
if(!inFile.is_open()) {
  // open failed..take necessary steps.
}
票数 2
EN

Stack Overflow用户

发布于 2010-10-11 21:39:34

我不能在dcp上评论上面的解决方案(还没有足够的帖子),你为什么不使用其他可用的擦除方法?为什么需要一个while循环?

您可以简单地调用:

foods.erase(0,loc);

(你不能这样做吗?)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3906529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档