我是c ++的新手,我的课和对象真的很糟糕。我找不到让用户输入数据的方法,而不仅仅是一些cout<<“..”;从我。我需要了解类和对象。我将衷心感谢您的帮助。我在论坛上搜索了一个类似的问题,我没有找到什么,如果我错过了,我真的很抱歉。
#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;
}
答案 0 :(得分:2)
答案 1 :(得分:2)
cout
将事情发送出去。 cin
发送内容。
这可能会有所帮助:
cin >> co.name;
答案 2 :(得分:2)
输出cout。 cin用于输入。
cin >> co.name
将值输入co.name
答案 3 :(得分:1)
如果您不想假设某个人的姓名是以空格分隔,请考虑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;
}