Display using void

Apr 10, 2009 at 3:46am
I have the following code, I need to display a message on screen, using a function on a class:

Class A
.
.
void getname1()
{
cout<<getname();
}
void getpoints1()
{
cout<<getpoints();
}
void printData()
{
cout<<"Player:";
getname1();
cout<<", score:";
getpoints1();
cout<<", ";
}
.
.
.int main()
{
.
.
.
cout<<"The winner is "<<winner.printData()<<endl;

I am getting error:error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion)

Any idea?I am not allowed to change main
Apr 10, 2009 at 4:17am
You are not supposed to be using void functions here. They need to return a value. Look here for more info:

http://www.cplusplus.com/doc/tutorial/functions/
Apr 10, 2009 at 12:03pm
Yes, I understand that. My problem is that
winner.printData()
is a combination of cout<< and variables and I am not allowed to change function call on main
Apr 10, 2009 at 12:15pm
closed account (z05DSL3A)
If you can not change the call in main() then you will have to change the return type of printData(). Build a string and return that.
Apr 10, 2009 at 7:54pm
Still, I have a string and some variables to return in the same line
Apr 10, 2009 at 8:33pm
You can use a stringstream to build the string
Apr 11, 2009 at 3:51pm
Any other ideas? On printData(), I have the following:
cout<<"Player:"<<getname()<<"points:"<<getpoints()<<endl;


I am able to change functions on class, but not main
Apr 11, 2009 at 4:52pm
why don't you replace 'cout' with a stringstream and then return the contents of that stream?
Apr 11, 2009 at 5:35pm
closed account (z05DSL3A)
This is the kind of thing you should do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <sstream>
 

class Player
{
public:
    Player(std::string name = "Anonymouse")
        : _name(name), _score(0)
    {
    }
    
    //...

    const int getpoints1()const 
    {
        return _score;
    }

    const std::string printData()const
    {
        std::stringstream ss;
        ss << "Player: " << _name << " score: " << getpoints1();
        return ss.str();
    }

private:
    std::string _name;
    int _score;
};

 
int main(int argc, char *argv[])
{
    using std::cout;
    using std::endl;

    Player winner;

    cout<<"The winner is "<<winner.printData()<<endl;

    return 0;
}
Topic archived. No new replies allowed.