저는 가속화 된 C++에서 제시된 몇 가지 개념을 이해하는 데 도움이 필요합니다. 여기 내가 문제가있는 곳입니다. read_hw의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;
}
정의() : 읽기()의
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);
}
정의 while (read(cin,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;
}
내가 지금까지 그것을 이해하는 방법은 우리가 호출 할 때이다 문자열 : record.name
및 두 개의 double
값 : record.midterm
및 record.final
. 사용자가 해당 데이터를 입력하면 우리 벡터에 있던 이전 요소를 지우는 read_hw()
함수를 입력합니다. 그런 다음 record.homework
이라는 숙제 등급의 벡터에 일련의 값을 입력하고 기록합니다. 나는 그걸 많이 이해하고 있다고 생각합니다. 그렇지 않다면 알려주세요.
우리 함수가 언제 복귀해야 하는지를 이해하지 못하기 때문에 첫 번째 while
루프로 돌아갑니다. 편집 : 아, 사용자가 프로그램을 끝내려면 두 번 파일 알림을 두 번 만들어야합니다. 그래서 나는 내 자신의 질문에 대답했다고 가정합니다. 그러나 누군가가 우리의 read_hw()
함수에서 if(in)
의 목적을 설명 할 수 있다면 매우 도움이 될 것입니다. if(cin)
이 될 것이므로 사용자가 데이터를 입력 할 때까지 기다리시겠습니까? 또는 if(cin)
이 자동으로 true입니까? (이유는 무엇입니까?)
이제 알겠습니다. 도움을 주셔서 감사합니다. 나는 그 기능이 작동하는 기본적인 방식을 이해했다. 하지만 이제는 파일 끝을 제외하고 if (cin) 표현식이 while 루프를 계속 실행할지 결정할 수 있는지를 확인했습니다. – zzz2991