1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
// read from a file, save to a struct.
#include <iostream>
#include <sstream> // This also includes 'string', so no need to include that too!
#include <fstream>
struct people
{
std::string name;
std::string surname;
int age;
};
int main()
{
//Create a const int that cannot be changed.
//This will serve as the amount of students and the loop for output.
const int count = 5;
people students[ count ]; //Create an array of your struct.
int i = 0; //indexer for your array.
//Change the variable 'input's name!
std::string input = "";
//Create an ifstream and open it.
std::ifstream iFile;
iFile.open( "myTextFile.txt" );
if( iFile.is_open() )
{
while( iFile.good() )
{
std::getline( iFile, input, ',' );
students[ i ].name = input; //Save the first name.
std::getline( iFile, input, ',' );
students[ i ].surname = input; //Save the surname.
std::getline( iFile, input, ',' ); //This is the field we don't want to save!
//So here, we don't do anything with 'input', then get the next field below.
getline( iFile, input, '\n' );//This is the age
//Create a stringstream object.
std::stringstream ss( input );
if( ! ( ss >> students[ i ].age ) )//If the conversion fails... To test, comment out the above /getline'
std::cout << "Error saving the age of student " << i + 1 << '\n';
++i; //Move to the next index. ( Error prone with this code. as I have an array of 5, whereas the file could contain more lines than index's!! )
//Break fron the while loop in case the file contains more than we need.
if( i == 5 )
break;
}
//Always close the files you open!
iFile.close();
}
else //If the file open failed...
std::cout << "Sorry! Unable to open the specified file.\n";
//Now we output the students.
for( int i = 0; i < count; ++i )
{
std::cout << "Student " << i + 1 << ":\n";
std::cout << students[ i ].name << " " << students[ i ].surname << " is " << students[ i ].age << "\n\n";
}
return 0;
}
|