2016-01-06 20 views
-3

所以我想创建一个加1的整数的函数每次有人回应是的,这是我的代码:C++:试图创建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; 
} 

所以我寻求帮助,和一些小技巧!

+3

'如果( “是” == “是”)'? – BlackDwarf

+0

这个程序是一个典型的案例,你应该阅读它,并试图说服自己,为什么它会做你想做的事情(因为它看起来好像没有)。将其分解成小任务,可能是逐行。 – mah

+0

只需更改为'if(yes ==“yes”)''。作为微不足道的问题结束投票。 –

回答

0

从这里开始:

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第二参数应该是一个参考。这样,当你在函数中改变它时,它将改变函数外部的变量,而不是它的副本。另外,如果你不希望这个函数返回任何东西,那么只需要返回类型void void yesToNumber(string yes, int &numberOfYes)此外,你现在将一个指向字符串的指针的值与另一个指向字符串的指针的值进行比较。我不认为这是你想要做的。我想你想比较字符串的内容。非常感谢std::string附带了一个功能,可以用简单的==来访问它。你想要做的是if(yes == "yes")。最后,在函数结尾处不需要yes = "";,因为std::cin无论如何都会覆盖字符串。

0

嘛。首先,你需要一个for循环,直到没有人离开。也许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循环中调用它。另外不要忘记, 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 
} 
相关问题