Рассмотрим версию getline()
, которая проживает в <string>
, если вы не хотите, чтобы предположить, что имя человека отделяется пробелами. Некоторые имена содержат более одного слова. Его также менее неуклюжий, чем cin.getline()
, поскольку вам не нужно указывать заранее максимальную длину чьего-либо имени.
#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: Модифицированная для использования оригинальных классов
#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;
}
Альтернатива: перегрузка операторов
#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;
}
спасибо большое – valkon
@valkongr вы можете, рад, что это помогло. – billz