Cevelop 对象到未初始化的变量 char 垃圾

Cevelop objects to un-initialized variable char junk

Cevelop 反对 char junk 作为 "un-initialized variable"。在这种情况下,解决问题的正确方法是什么?

 friend std::ostream& operator<<(std::ostream& os_a, College& college_a) {
   return os_a <<  college_a.id_ + ' ' + college_a.name_;
 }

 friend std::istream& operator>>(std::istream& is_a, College& college_a) {
   char junk;
   return is_a >> college_a.id_ >> std::noskipws
       >> junk, std::getline(is_a, college_a.name_);  // name: between 1st space and endofline.
  }

您有两个选择,您可以将 junk 初始化为某个东西,或者您可以直接删除它。因为你知道你只需要吃掉一个 space 你然后使用 get 就像

return is_a >> college_a.id_, is_a.get(), std::getline(is_a,college_a.name_);

它会做同样的事情。您还可以使用

使代码更易于阅读
is_a >> college_a.id_;
is_a.get();
std::getline(is_a,college_a.name_);
return is_a;