Hi i want to read in a text file and store the contents into a list in C++. I am able to read in the file using fstream.
I have declared a list of type string however the contents of the text file has employee ID number which is of type int. Is is appropriate to store the employees into a list of type string?
How could i modify this code so i can store the contents into the "list "of employees?
Thanks.
Here is my attempted code:
#include %26lt;iostream%26gt;
#include %26lt;list%26gt;
#include %26lt;fstream%26gt;
#include %26lt;string%26gt;
using namespace std;
int main ()
{
int iQuit = 0;
list%26lt;string%26gt; employees;
cout %26lt;%26lt; "test";
return 0;
string str;
ifstream myFile("Employees.txt");
if(! myFile)
{
cout %26lt;%26lt; "Error opening the file" %26lt;%26lt;endl;
return -1;
}
while(! myFile.eof())
{
getline(myFile, str);
cout %26lt;%26lt; str %26lt;%26lt; endl;
}
myFile.close();
cin %26gt;%26gt; iQuit;
return 0;
}
Reading text files and storing contents into a List C++?
Unless you are going to perform some kind of math on the employee numbers, I don't see what the problem is representing them strings. You could save some small amount of space by storing them as integers but I doubt that is an issue here.
As for storing the contents of the lists just use the list push_back() method like so:
while (! myFile.eof())
{
getline(myFile, str);
cout %26lt;%26lt; str %26lt;%26lt; endl;
employees.push_back(str);
}
If you really do want to use integers basically all you need to do is to change to a list%26lt;int%26gt; for employees and convert the string to an int using atoi or a stringstream.
gerbera
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment