简体   繁体   English

C ++字符串用户输入到类对象?

[英]C++ String user input into Class Object?

Let's say i have some class Employee ,and an object Director. 假设我有一些类Employee和一个对象Director。 For example : 例如 :

#include <iostream>
using namespace std;

 class Employee
{
 public:
 string firsName;
 string lastName;
 int age;
};

 int main()
{
 Employee Director;
 Director.firstName = "Smith";
 etc....
}

etc...

return 0:
}

How i use a String input to let the user enter Director.firstName and etc. into the object? 我如何使用字符串输入让用户在对象中输入Director.firstName等?

cout<<"Enter Directors name: " << endl;
Director.firstName = getline(cin ,firstName);

Thank u very much in advance ! 提前非常感谢您!

change Director.firstName = getline(cin, firstName); 更改Director.firstName = getline(cin, firstName); to getline(cin, Director.firstName); getline(cin, Director.firstName);

The function getline is used differently. getline函数的用法不同。 You should pass the string as a reference in which the result should be written. 您应该将字符串作为引用写入结果,并在其中引用。 The return value of the function is a reference to the stream, which you can ignore. 该函数的返回值是对流的引用,您可以忽略该流。

In order to pass the firstName you need to add the object of which you want to access the member, like you originally did with the left hand of the assignment. 为了传递firstName您需要添加要访问其成员的对象,就像您最初使用分配的左手所做的那样。

getline(cin, Director.firstName);

So don't use the assignment operator ( = ) here. 因此,请勿在此处使用赋值运算符( = )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM