Search code examples
c++functionstrcmp

strcmp in a function in c++


I am just trying to learn how to use c++ and one thing that I am trying to make is a yes or no choice "choose y to continue choose n to exit" kinda thing I know other ways of doing this other then this method but I am trying to learn the concept of creating functions outside of main() better this is the code I am trying to use

int yesorno(char yn[]);

int yesorno(char yn[])
{
   int a=0;
   do 
   {
       if (!strcmp( yn , "y" || yn , "Y"))
        {    
           a=1;
        }
       else if (!strcmp( yn , "n" || yn ,"N"))
        {
           a=2;
        }
       else 
        {
           cout<<"Please choose y or n \n";
           cin>> yn;
           a=3;
        }

   }while (a==0 || a>=3);
   yn = "0";
   return a;
}

the error I get is "no matching function for call to 'strcmp' " in the if and else if statement yet using strcmp in main() works just fine and I have #include just wondering what I am doing wrong with this. Any help is very very much appreciated.


Solution

  • You can't insert boolean conditions into the function this way:

    if (!strcmp( yn , "y" || yn , "Y"))
    

    change the conditions to first evaluate the boolean result of the functions and then perform your logical comparison

    if (!strcmp(yn , "y") || !strcmp(yn , "Y"))
    

    Also notice that you're missing #include <cstring> to use strcmp