我在這裏要求幫助理解加速C++中提出的一些概念。這是我遇到問題的地方。if(cin)的用途?
istream& read(istream& is, Student_info& s)
{
// read and store the student's name and midterm and final exam grades
is >> s.name >> s.midterm >> s.final;
read_hw(is, s.homework); // read and store all the student's homework grades
return is;
}
定義read_hw的():讀取()的
vector<Student_info> students; //Student_info is a structure we made
Student_info record;
string::size_type maxlen = 0;
// read and store all the records, and find the length of the longest name
while (read(cin, record)) { //Here is where I find hard to follow
maxlen = max(maxlen, record.name.size());
students.push_back(record);
}
定義
// read homework grades from an input stream into a vector<double>
istream& read_hw(istream& in, vector<double>& hw)
{
if (in) {
// get rid of previous contents
hw.clear() ;
// read homework grades
double x;
while (in >> x)
hw.push_back(x);
// clear the stream so that input will work for the next student
in.clear();
}
return in;
}
我瞭解到目前爲止的方式是,當我們致電:while (read(cin,record))
我們要求字符串:record.name
和兩個double
值:record.midterm
和record.final
。在我們的用戶輸入了這些數據後,我們將輸入我們的read_hw()
函數,我們將清除之前可能在我們的矢量中的元素。然後,我們輸入並記錄一組值爲一個稱爲record.homework
的家庭作業向量。我想我很瞭解這一點。如果沒有,請讓我知道。
我不明白我們的函數知道什麼時候返回,因此返回到我們的第一個while
循環。編輯:啊,用戶必須做兩次和結束文件通知結束程序。所以我想我回答了我自己的問題......但是有人能夠在我們的read_hw()
函數中解釋if(in)
的用途,這將會非常有幫助。這將是if(cin)
,那麼等待我們的用戶輸入數據?或者是if(cin)
自動爲真? (爲什麼?)
現在我明白了。謝謝你們的幫助。我有點理解該函數的基本工作方式。但是現在我看到if(cin)表達式,特別是除了文件結束之外,可以決定我們是否繼續運行while循環。 – zzz2991