这似乎给我带来了一点麻烦。此方法应生成一个随机数并将其分配给一个char。getline从文本文件中获取整个字符串,并将其分配给食品。Y的目的是保持它在食品字符串中找到c的位置。然后,它将使用int从字符串中擦除,并打印出剩下部分。
我一直收到"Program has requested to shutdown up an runtime error in a unusual“的提示,然后它就被锁住了。提前谢谢。
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;
}发布于 2010-10-11 21:18:43
尝试:
请注意,foods.erase(y)将擦除'f‘前面的字符。如果您想要擦除'f‘以下的字符,请参阅此示例:
下面是一个简单的擦除字符的例子:
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;程序输出:
---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
ghijk
> Terminated with exit code 0.因此,对于您的示例,您需要类似以下内容:
while(y >= 0) {
foods.erase(foods.begin() + y);
--y;
}while编辑您还可以消除while循环,只需调用重载的erase,如下所示:
string x = "abcdefghijk";
int loc = x.find('f');
if (loc >= 0) {
x.erase(x.begin(),x.begin()+loc+1);
cout<<x<<endl;
}程序输出:
---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
ghijk
> Terminated with exit code 0.发布于 2010-10-11 21:22:38
如果find方法在字符串foods中找不到c怎么办?它返回npos,当你在erase中使用它时,你的程序失败了。
因此,您需要在执行erase之前添加此检查
y = foods.find(c);
if( y != string::npos) {
foods.erase(y);
}此外,在您尝试从文件open中读取一行之前,您应该始终确保该文件成功。
inFile.open("OatmealFood.txt", ios::in);
if(!inFile.is_open()) {
// open failed..take necessary steps.
}发布于 2010-10-11 21:39:34
我不能在dcp上评论上面的解决方案(还没有足够的帖子),你为什么不使用其他可用的擦除方法?为什么需要一个while循环?
您可以简单地调用:
foods.erase(0,loc);
(你不能这样做吗?)
https://stackoverflow.com/questions/3906529
复制相似问题