【问题标题】:Reference not changing the value of variable参考不改变变量的值
【发布时间】:2020-04-24 07:52:09
【问题描述】:

我编写了这个程序来查找用户给定字符串中字符的第一次出现以及该字符的频率。但是当我在主函数中打印变量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;
}

【问题讨论】:

  • 因为没有指定打印i_r或调用find_ch的顺序。如果在调用函数之前打印了i_r,您将看到零。只需在下一行打印i_r
  • 即使是有经验的程序员也常认为在cout &lt;&lt; E1 &lt;&lt; E2E1 必须在E2 之前进行评估,但事实并非如此(正如您所发现的那样)。跨度>
  • 要在字符串中找到一个字符 C++ 有std::string::find 并计算一个字符的出现次数我们有std::count

标签: c++ function reference pass-by-reference


【解决方案1】:

到这里你的问题就解决了。只需在 cout 语句之前执行该函数。正在发生的是,在打印中,它遵循从右到左的顺序执行。您也可以使用 printf 函数在 C 语言中体验到这一点。我从中获得了很多乐趣,并在数字上使用 ++ 或 -- 运算符并打印它们。它们递增和递减的顺序让您感到困惑。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2012-09-13
    相关资源
    最近更新 更多