C++:尝试创建一个函数,当有人在控制台中说 "yes" 时将整数加 1

C++ : Trying to create a function that add 1 to an integer when someone say "yes" in the console

所以我正在尝试创建一个函数,每当有人回答是时,它就会将整数加 1,这就是我的代码:

#include "yesToNumber.h"
#include <string>

using namespace std;


int yesToNumber(string yes, int numberOfYes)
{
    if ("yes"=="yes")
    {
        numberOfYes++;
        yes = "";
    }
}

但我不知道在我的主要代码中该把函数放在哪里:

#include <iostream>
#include <string>
#include "yesToNumber.h"


using namespace std;

int main()
{
    string agree, dontAgree;

    cout<<"The question is : Do you have a computer ? Please answer with yes or no."<<endl;
    cout<<"You have a computer."<<endl;
    cin>>agree;
    cout<<"You don't have a computer."<<endl;
    cin>>dontAgree;

    cout<<"number of people who said yes : "<<agree<<" / number of people who said no"<<dontAgree<<endl;



    return 0;
}

所以我正在寻求帮助和一些提示!

嗯。首先,您需要一个 for-loop,它将 运行 直到没有人离开。可能有10个人在问,做运行10次

你的函数有问题。

if ("yes"=="yes")// this is always true. Remove the " " around the first yes
if (yes == "yes") // This checks if what the user entered is equal to yes.

然后你就可以在你的for-loop里面调用它了。也不要忘记 numberOfYes 必须通过引用发送。否则,您将更改 numberOfYes 的副本而不是原始变量。

yesToNumber(string yes, int& numberOfYes) // added & after int

小样本:

std::string answer;
int numberOfYes = 0;
for(int i = 0; i < 3; i++)
{
    cin >> answer;
    yesToNumber(answer, numberOfYes ); // Calling the function 
}

从这里开始:

int main()
{
    int numberOfYes = 0;

    for(int number_of_people = 10, people_asked = 0; people_asked < number_of_people; people_asked++ )
    {
        std::cout << "Do you have a computer?";
        std::string answer;
        std::cin >> answer;
        yesToNumber(answer, numberOfYes);
    }

    std::cout << numberOfYes;
    return 0;
}

for 循环询问您是否有计算机,得到您的答案,然后调用处理该信息的函数。

虽然你的函数有一些问题。

对于初学者来说,yesToNumber的第二个参数应该是一个参考。这样,当您在函数中更改它时,它正在更改函数外部的变量而不是它的副本。此外,如果您不希望此函数 return 任何内容,则只需将 return 类型设置为 void void yesToNumber(string yes, int &numberOfYes) 另外,现在您正在比较指向字符串的指针的值另一个指向字符串的指针的值。我不认为那是你想要做的。我想你想比较字符串的内容。谢天谢地 std::string 有一个函数可以做到这一点,并且可以通过简单的 == 访问它。你要做的是if(yes == "yes")。最后,您不需要在函数末尾使用 yes = "";,因为 std::cin 无论如何都会覆盖字符串。