Hi guys. can someone help me? my problem is that i want to put the data i streamed to a file back to the struct but i dont know how to do that. heres my program.
#include <iostream>
#include <fstream>
#include <string>
struct student {
std::string name;
int age;
std::string course;
};
// write student info to an output stream (like std::cout or an output file stream)
std::ostream& put_student( std::ostream& stm, const student& s ) {
return stm << s.name << '\n' // name in the first line
<< s.age << '\n' // age in the second line
<< s.course << '\n' ; // course in the third line ;
}
// read student info from an input stream (like std::cin or an input file stream)
std::istream& get_student( std::istream& stm, student& s ) {
std::getline( stm, s.name ) ; // read name from the first line
stm >> s.age // read age from the second line
>> std::ws ; // skip over the new line to get to the third line
return std::getline( stm, s.course ) ; // read course from the third line ;
}
int main() {
student my_students[] { { "bugs bunny", 3, "intro to C++" }, { "woody woodpecker", 1, "C++ 102" } } ;
{
// write to an output file
std::ofstream file( "students.txt" ) ; // open the file for output
for( const student& s : my_students) put_student( file, s ) ;
}
{
// read from the file and print to stdout
std::ifstream file( "students.txt" ) ; // open the file for input
student s ;
while( get_student( file, s ) ) put_student( std::cout, s ) << "-----------\n" ;
}
}
hi. thanks for helping. Im new to programmin so i dont understand a thing about that program. We only covered the basics in class so sorry about that. what is stm? why is there a const before student? and what is the meaning of the parameters on your loops? oh and i tried to run your program but i get an error on line 36 saying "range based 'for' loops are not allowed in C++98 mode".
stm is the name of the variable (of type 'reference to input or output stream').
We can think of it as another name for the stream object.
For example, in the call put_student( file, s ) ;, stm becomes an alias for the input file stream file
> why is there a const before student?
Because the student object need not be a modifiable object; we only want to read from it.
> and what is the meaning of the parameters on your loops?