Reputation: 43
I am new to c++ and am following a online tutorial, i have copied this guys code multiple times and cannot figure out what is wrong. it just outputs garbled text.
I am using code::blocks
This is what it outputs (the link below)
https://gyazo.com/9c2786ef20fb3878354a72904d126f7e
My Actual Code
main.cpp
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
Person person;
cout << person.toString() << endl;
return 0;
}
Person.cpp
#include "Person.h"
#include <sstream>
Person::Person()
{
age = 0;
name = "jeff";
}
string Person::toString(){
stringstream ss;
ss << "Name: ";
ss << name;
ss << "; age: ";
ss << age;
}
Person.h
#ifndef PERSON_H
#define PERSON_H
#include <iostream>
using namespace std;
class Person{
private:
string name;
int age;
public:
Person();
string toString();
};
#endif // PERSON_H
Upvotes: 2
Views: 63
Reputation: 520878
You had two problems with your code. You were never returning a value and also you should using stringstream.str()
:
int main()
{
Person person;
cout << person.toString() << endl;
return 0;
}
string Person::toString() {
stringstream ss;
ss << "Name: ";
ss << name;
ss << "; age: ";
ss << age;
return ss.str();
}
Upvotes: 4