First of all according to the SO rules you should provide MCVE when asking a question. Secondly, you should avoid using namespace std;
as it opens up the floodgates of global namespace pollution. You can do things like using std::cout;
for convenience without opening up the whole standard namespace. Finally, life would be easier if you just used std::string
instead of char[]
in your struct
but anyway here is the basic idea. You can read the age and name directly from your input file into local variables then set your structure elements from those input values. This is assuming that every line of your input file is as you say it is, and there is no error checking.
#include <fstream> // for std::ifstream
#include <string> // for std::string
#include <cstring> // for strcpy()
std::ifstream infile("garbage.txt");
if (infile.is_open())
{
int age;
std::string namestr;
while (infile >> age >> namestr)
{
stud1 temp;
temp.age = age;
strcpy( temp.name, namestr.c_str() );
// do whatever before struct goes out of scope
}
infile.close();
}