Reference not changing the value of variable

房东的猫 提交于 2021-01-29 02:04:08

问题


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.

Why is this happening?

#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;
}

回答1:


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;
}


来源:https://stackoverflow.com/questions/61403626/reference-not-changing-the-value-of-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!