Question

i am new to c++ and i have a really bad time with classes and objects. I can't find a way to make the user to enter the data and not just some cout <<".."; from me. I need to understand classes and objects . I would really appreciate your help. I searched the forum for a similar question and i didn't find something, if i missed it i am really sorry .

#include <iostream>
#include <string>

using namespace std;

class ManosClass{
public:
    string name;
};

int main ()
{
    ManosClass co;
    co.name =          //i want here the user to enter his name for example and i can't figure a way to do this
    cout << co.name;
    return 0;
}
Was it helpful?

Solution

To read user input, you are looking for see std::getline or use std::cin

std::getline(std::cin, co.name);

or

std::cin >> co.name;

OTHER TIPS

cout sends things out. cin sends things in. This might help:

cin >> co.name;

cout is output . cin is used for input.

 cin >> co.name

enter the value into co.name

Consider the version of getline() which resides in <string> if you don't want to assume that a person's name is white space separated. Some names do contain more than one "word". Its also less clumsy than cin.getline() since you don't need to specify in advance the maximum length of someone's name.

#include <iostream>
#include <string>
using namespace std;

int main()
{
   string strName;
   getline(cin, strName); //Will read up until enter is pressed
   //cin >> strName //will only return the first white space separated token
   //Do whatever you want with strName.
}

Edit: Modified for to use original classes

#include <iostream>
#include <string>

using namespace std;

class ManosClass{
public:
    string name; //You might want to look at rather not using public data in a class
};

int main ()
{
    ManosClass co;
    getline(cin, co.name);
    cout << co.name;
    return 0;
}

Alternative: Operator overloading

#include <iostream>
#include <string>

using namespace std;

class ManosClass{
public:
     friend ostream& operator<<(ostream& out, const ManosClass& o);
     friend istream& operator>>(istream& in, ManosClass& o);
private:
    string name; //Hidden from prying eyes
};

ostream& operator<<(ostream& out, const ManosClass& o)
{
    out << o.name;
    return out;
}

istream& operator>>(istream& in, ManosClass& o)
{
    getline(in, o.name);
    return in;
}

int main ()
{
    ManosClass co;
    cin >> co; //Now co can be used with the stream operators
    cout << co;
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top