stringstream format

Hi, i have a problem with this code. I want to return the string temp in a tabular way, so i think to use setw and left. Something's wrong because maybe stringstream don't "accept" setw and left. Is there a different way to do it?
Note that _person is a class.

string Student::str() const
{
string temp;
stringstream ss;
ss<<left<<setw(5)<<_person.name()<<setw(5)<<_person.surname<<setw(5)<<_person.gender();
ss>>temp;
return temp;
}

Last edited on
what exactly are you trying to do? print Student objects by overloading the << operator?
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
44
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip> // required for std::setw

struct person
{
    std::string _name ;
    std::string _surname ;
    std::string _gender ;

    std::string name() const { return _name ; }
    std::string surname() const { return _surname ; }
    std::string gender() const { return _gender ; }
};

struct Student
{
    person _person ;

    std::string str() const
    {
        std::ostringstream stm ;

        stm << std::left
            << std::setw(15) << _person.name()
            << std::setw(15) << _person.surname()
            << std::setw(8) << _person.gender() ;

        return stm.str() ;
    }

    friend std::ostream& operator<< ( std::ostream& stm, const Student& s )
    { return stm << s.str() ; }
};

int main()
{
    Student arr[] { { { "Bjarne", "Stroustrup", "Male" } }, { { "Barbara", "Moo", "Female" } } } ;

    for( const Student& s : arr ) std::cout << s.str() << '\n' ;
    std::cout << '\n' ;
    for( const Student& s : arr ) std::cout << s << '\n' ;
}

http://coliru.stacked-crooked.com/a/ce93d3fbd4b0e3c4
Thank you a lot!!
Topic archived. No new replies allowed.