参考未更改变量的值

问题描述 投票:1回答:1

我已经编写了此程序,以在给定字符串和字符出现频率的情况下找到用户中该字符的首次出现。但是,当我在主函数中打印变量i_r的值时,它将打印零。但是在find_ch边显示正确的值。

为什么会这样?

#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;
}
c++ function reference pass-by-reference
1个回答
0
投票

这里您的问题已解决。只需在cout语句之前执行函数即可。发生的是在打印中,它遵循从右到左的顺序执行。您也可能会在C中使用printf函数遇到这种情况。我对此感到很有趣,并使用++或-运算符对数字进行打印。有点让您感到困惑的是它们的递增和递减顺序。

#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.