簡體   English   中英

為什么cin.getline分配給字符數組,但不使用'='?

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

例如,如果我從某個用戶那里獲得學生姓名,並使用cin.getline(student.name, 50); 我可以分配學生姓名。 我無法通過student.name = "John Doe";來明確分配學生姓名student.name = "John Doe"; 因為您不能只復制數組,但是當我使用getline函數時為什么這樣做有效? 有什么區別? 是不是getline()收集字符數組然后將其復制到studnet.name呢?

為了澄清cin.getline(student.name, 50) ,我cin.getline(student.name, 50)為什么我可以使用cin.getline(student.name, 50)分配一個學生姓名,而不是stuent.name = "John Doe" ,這兩種方法有什么區別(為什么getline()有效,而直接分配無效。)。

請參閱以下C常見問題解答-http: //c-faq.com/aryptr/arrayassign.htmlhttp://c-faq.com/aryptr/arraylval.html

我在這里假設name是一個char name[something]

如果要分配,請使用std::string類型而不是char array

改變你的

char name[50];

#include <string>
using std::string;

... ...

    string name;

... ...

現在,您可以隨意使用=

getline之所以有效,是因為在內部它會做這樣的事情

  • 讀一個字符。

  • 分配給名稱[0]

  • 閱讀下一個字符。

  • 分配給名稱[1]。

等等。

如果查看istream :: getline函數的參數列表,則istream& getline (char* s, streamsize n ); ,您會注意到它使用您的變量student.name作為指針。 這使getline可以直接寫入c字符串的內存位置。

編輯:請參閱注釋中的Praetorian的答案以獲取更詳細的解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM