Results 1 to 3 of 3

Thread: C++ Functions

  1. #1

    Thread Starter
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    Does anyone know how i can have a funcion return a string?
    char wintest(int x1,int y)
    {
    if ((count1==1)||(count1 == 3) || (count1 == 5) || (count1 ==7) || (count1 == 9))
    return win;
    }


    // this is declared before the main
    char win []= {
    "Player 1 is the winner",
    };

    so as far as i can tell win should hold the string but char only returns one character. so basically im stuck. any suggestions?
    thanxxxxx

  2. #2
    Guest
    You can do the following
    #include<string> //if you are using VC++

    using namespace std

    string something()
    {
    return "Hello everyone.";
    }

    int main(int argc,char *argv[])
    {
    string ret;
    ret=something;
    cout << ret.c_str();
    return 0;
    }

    or return a character pointer#include<fstream.h>

    char * hi()
    {
    char * ret;
    ret="hi";
    return ret;
    }

    void main()
    {
    char * ret;
    ret=hi();
    cout << ret;
    }


  3. #3
    Lively Member
    Join Date
    Jan 1999
    Location
    Rochester NY, USA
    Posts
    93
    Do this..

    //char wintest(int x1,int y)
    //make the function return a pointer to a string.
    char * wintest(int x1, int y)
    {
    if ((count1==1)||(count1 == 3) || (count1 == 5) || (count1 ==7) || (count1 == 9))
    return win;
    }


    // this is declared before the main
    //char win []= {
    //"Player 1 is the winner",
    //};
    //create a pointer to the string...
    char *win = "Player 1 is the winner";

    The problem is that the function is declared as a char.. that's not a string. That's one character. Your array "win" is kind of creating a pointer.. so saying that you want to return "win" is actually saying "return win[0]". win is actually a pointer to the first element in the array. You really want to return a pointer to the array, or you're going to want to use strcpy (better to use strncpy) to copy the text to where you want it. All depends on what you want to do.



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width