【发布时间】:2015-09-29 17:49:48
【问题描述】:
Book.h:
#ifndef BOOKDATE
#define BOOKDATE
#include <iostream>
#include <string>
class Book{
friend std::istream& operator>>(std::istream&, Book&);
private:
std::string title, author;
int number;
};
std::istream& operator>>(std::istream&, Book&);
#endif // BOOKDATE
Book.cpp:
#include "BookDate.h"
using namespace std;
istream& operator>>(istream& is, Book& rhs){
getline(is, rhs.title);
getline(is, rhs.author);
is >> rhs.number;
if(!is)
rhs = Book();
return is;
}
我想知道我应该如何为Book 类创建输入运算符。 title 和 author 将超过一个词,因此我需要使用 getline 来接收该数据。然后getline 的问题是它可能会拾取自上次使用cin 以来留在流中的任何'\n'。比如;
int x;
cin >> x; //newline is not extracted and left behind
Book a;
cin >> a; //"title" is automatically made empty!
我可以改用cin.ignore(256, '\n'),但谁的责任,用户或author的类,是使用这个吗?用户在输入Book 对象之前是否使用.ignore,或者类作者是否将.ignore 放在输入操作的开头?
似乎在前一种情况下,用户必须了解.ignore 方法是必需的,但这样做必须了解Book 的输入运算符的实现,这是不可取的。在后一种情况下,将.ignore 放在运算符中意味着我的运算符可能无法适应某些情况,因为它总是希望在处理之前遇到换行符。例如从输入文件中读取数据,例如:
book1
author1
1
book2
author2
2
意味着book1 被cin.ignore(256,'\n') 忽略。
【问题讨论】:
-
我会说
operator>>()应该假定文件处于开始阅读的正确位置。 -
另外
operator>>()在阅读前跳过空格也不是没有道理的。 -
正常约定是假定流正确定位在要读取的对象的开头。您定义您的对象是否可以或不能以换行符开头。您的调用者负责定位流
标签: c++ input operator-keyword getline