简体   繁体   中英

Why does cin.getline assign to character array but using '=' will not?

For instance, if I am getting student names from a user and use cin.getline(student.name, 50); I can assign student names. I cannot explicitly assign a student name via student.name = "John Doe"; since you cannot just copy an array over, but why does this work when i use the getline function? What is the difference? Isn't getline() collecting a character array and then copying it to studnet.name anyway?

For clarification, I'm asking why I can use cin.getline(student.name, 50) to assign a student name but not stuent.name = "John Doe" and what is the difference between the 2 methods (why the getline() works and the direct assignment does not work).

See the following C FAQ questions - http://c-faq.com/aryptr/arrayassign.html and http://c-faq.com/aryptr/arraylval.html .

I am assuming here that name is a char name[something] .

If you want to assign, use the std::string type instead of a char array

Change your

char name[50];

to

#include <string>
using std::string;

... ...

    string name;

... ...

Now you can use = like you want to.

getline works because internally it would do something like this

  • read one char.

  • assign to name[0]

  • read next char.

  • assign to name[1].

and so on.

If you look at the parameter list of the istream::getline function, istream& getline (char* s, streamsize n ); , you will notice that it takes your variable, student.name , as a pointer. This allows getline to write directly to the memory location of your c-string.

edit: see Praetorian's answer in the comments for a more detailed explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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