如果您不想假设一个人的名字是空格分隔的,请考虑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.
}
编辑:修改为使用原始类
#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;
}