我正在编写一个程序,以返回字符的首次出现以及该字符在字符串中的出现频率。该函数中的for循环执行无限次,并且条件和块甚至不执行一次。
怎么了?
string::size_type find_ch(string &str,char ch,int& i_r)
{
string::size_type first=0;
for(auto i=str.size()-1;i>=0;i--)
{
cout<<"\nInside a for loop."<<endl;
if(str[i]==ch)
{
cout<<"Inside if."<<endl;
first=i+1;
i_r++;
}
}
return first;
}
此循环:
for(auto i = str.size() - 1; i>=0; i--)
仅在i
小于0
时退出。但这不是unsigned int
的有效值。该值将换为最大值unsigned int
,您将获得无限循环。
请注意,.size()
上的std::string
返回size_t
,它基本上是unsigned int
类型。
解决此问题的一种方法是将.size()
的返回类型强制转换为int,如下所示:
for(auto i = static_cast<int>(str.size()) - 1; i>=0; i--)
请注意,进行强制转换before减去1很重要。