C++ 函数没有返回我想要的值

C++ 函数没有返回我想要的值,c++,C++,我希望能够接受用户输入并为给定的字母赋值。我想我把那部分搞定了,现在问题是返回值 #include <iostream> #include <string> using namespace std; int ch2n(string word); int main() { string inputWord; cout << "Type Word: "; cin >> inputWord; cout <

我希望能够接受用户输入并为给定的字母赋值。我想我把那部分搞定了,现在问题是返回值

#include <iostream>
#include <string>
using namespace std;

int ch2n(string word);

int main()
{
     string inputWord;

     cout << "Type Word: ";
     cin >> inputWord;
     cout << ch2n(inputWord);
}

int ch2n(string word)
{
    int total = 0;
    for(int i = 0;i != word.size(); i++)
    {
        if(word.find(i) == 'a' || word.find(i) == 'A')
        {
            total += 1;
        }
    }
    return total;
}
#包括
#包括
使用名称空间std;
int-ch2n(字符串字);
int main()
{
字符串输入字;
cout>输入字;

cout如果不初始化它(设置它的值),使用它是未定义的行为,可以返回任何随机值,包括0

没有构造函数的类型,如
int
,将只分配空间并具有一个未定义的值,通常基于先前使用时在该位置发生的任何情况

word.find
不做你认为它做的事,它在
word
中搜索
i

您只需使用
word[]

if(word[i] == 'a' || word[i] == 'A')

另外,您可能希望将
std::endl
放在
cout
行的末尾

我认为
word.find(I)
可能不是您想要在那里调用的。要访问字符串中的特定字符,请使用方括号,即:
word[I]
而不是
word.find(I)如果你不声明它是0,你的结果是随机的,因为C++,C,不初始化数据。如果你声明一个变量,比如Total,初始值就是在内存中的任何地方。它可能真的是任何东西。总是初始化变量的值。< /P>
我认为您没有返回任何有意义的内容的原因是因为您使用的查找错误。std::string::find不返回布尔值,如果返回位置。因此,您需要检查字符串位置是否表示“此字符串中不存在字符”。这就是std::string::npos。因此,您需要:

    if(word.find('a') != string::npos || word.find('A') != string::npos){
        total += 1;
    }

例如,当我输入一个单词,字母a或单词Apple时,当我想将值增加1时,我仍然得到0的返回值。这是另一个问题:)还有其他问题吗,或者你的问题得到了回答吗?我的问题已经得到了回答。我必须说,这个社区绝对棒极了。很高兴我最终加入了,而不仅仅是躲在谷歌s上搜索结果。请随意对任何有帮助的答案进行投票,如果您觉得提供了答案,请选择一个答案,我们也很高兴能够提供帮助。更好的方法是使用
tolower(word[i])='a'
而不是
word.find(i)='a'| word.find(i)=='A'
@user2509848谢谢,这比使用or运算符要好得多。或者,您可以调用
http://en.cppreference.com/w/cpp/algorithm/count
只需在
intmain()上面编写函数
intch2n()
而不是使用声明。我认为您对string.find的使用需要重新思考
word。find(I)='a'!=string::npos
如果
npos
不是零或一,则结果总是真的。因为
npos
不是零或一
total
总是递增的。是的,你是对的。我的意思是word.find('a'))!=字符串::npos。看起来他只是在尝试迭代字符。如果文本是“bbbbb a”,结果将是6,因为每次调用
find
都会成功,因为
a
位于字符串的末尾。您只想检查
i
的当前位置/索引处的字符。