问题描述
我编写了这个程序来查找用户给定的字符串中该字符的第一次出现和该字符的频率.但是当我在主函数中打印变量 i_r
的值时,它打印零.但是在侧面 find_ch
它显示正确的值.
I have written this program to find the first occurrence of the character in the user given string and frequency of that character. But when I print the value of variable i_r
inside the main function it prints zero. But in side find_ch
it shows right value.
为什么会这样?
#include<iostream>
#include<string>
using namespace std;
string::size_type find_ch(string &str,char ch,int &i_r)
{
string::size_type first=0;
for(auto i=static_cast<int>(str.size())-1;i>0;i--)
{
cout<<"Value of i_r : "<<i_r<<endl;
if(str[i]==ch)
{
first=i+1;
i_r++;
}
}
return first;
}
bool check_char(string &str,char ch)
{
for(auto i=str.begin();i!=str.end();i++)
if(*i==ch)
return 1;
return 0;
}
int main()
{
string str,&rstr=str;
char ch=' ';
int freq=0,&i_r=freq;
cout<<"Enter a string : ";
getline(cin,str);
cout<<"Enter a character you want to find first occurrence index and count : ";
cin>>ch;
if(check_char(rstr,ch))
cout<<"First occurrence of character "<<ch<<" is "<<find_ch(rstr,ch,i_r)<<" and frequency of character is "<<i_r;
else
cout<<"Character does not exist in the string.";
return 0;
}
推荐答案
到这里,你的问题就解决了.只需在 cout 语句之前执行该函数即可.发生的事情是,在打印时,它遵循从右到左的顺序执行.您可能也会在 C 中使用 printf 函数体验到这一点.我对此很感兴趣,并在数字上使用 ++ 或 -- 运算符并打印它们.它们递增和递减的顺序会让您感到困惑.
Here your problem is solved. Just execute the function before the cout statement. What is happening is that in printing, it follows the order from right to left for execution. You might experience this in C also using printf function. I had loads of fun with that and using ++ or -- operators on number and printing them. It kind of baffles you with the order in which they are incrementing and decrementing.
#include<iostream>
#include<string>
using namespace std;
string::size_type find_ch(string &str,char ch,int &i_r)
{
string::size_type first=0;
for(auto i=static_cast<int>(str.size())-1;i>0;i--)
{
cout<<"Value of i_r : "<<i_r<<endl;
if(str[i]==ch)
{
first=i+1;
i_r++;
}
}
return first;
}
bool check_char(string &str,char ch)
{
for(auto i=str.begin();i!=str.end();i++)
if(*i==ch)
return 1;
return 0;
}
int main()
{
string str,&rstr=str;
char ch=' ';
int freq=0,&i_r=freq;
cout<<"Enter a string : ";
getline(cin,str);
cout<<"Enter a character you want to find first occurrence index and count : ";
cin>>ch;
if(check_char(rstr,ch))
{
auto a = find_ch(rstr,ch,i_r);
cout<<"First occurrence of character "<<ch<<" is "<<a<<" and
frequency of character is "<<i_r;
}
else
cout<<"Character does not exist in the string.";
return 0;
}
这篇关于引用不改变变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!