Hi, I'm having trouble figuring out how to store 4 ints separated by a '.' and a string from a "hosts.txt" file which contains:
111.22.3.44 platte
555.66.7.88 wabash
111.22.5.66 green
555.66.11.24 homer
123.45.67.89 loner
12.34.56.78 pizza
555.66.9.10 ulysses
0.0.0.0 none
Here is my code so far
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
|
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct ADDRESS_TYPE
{
int a;
int b;
int c;
int d;
string name;
};
int ReadRecord(ADDRESS_TYPE &m, istream &in)
{
int temp;
in >> m.a, m.b, m.c, m.d; // trying to store the ints into int variables of the struct a, b, c, d
getline(in, m.name); // read the string and store into c++ string of struct
temp = m.a + m.b + m.c + m.d; // checks to see if the ip address is 0.0.0.0
if(temp == 0)
{
cout << "0.0.0.0 record read" << endl;
return -1;
}
else
{
return 0;
}
}
int main()
{
int count = 0;
int done = -1;
int result;
ADDRESS_TYPE m[200]; // array of structs
ifstream in;
char infilename[150];
cout << "What is the input file name?: " << flush; // get input file name
cin >> infilename;
in.open(infilename);
if(!in)
{
cout << "Error opening the input file. Exiting." << endl;
return 0;
}
while(count < 200 && ReadRecord(m[count++],in)!=done); // reads input file until 0.0.0.0 record is read
for(int x = 0; x < count; x++) // test print of struct
{
cout << m[x].a << "." << m[x].b << "." << m[x].c << "." << m[x].d << "\t";
cout << m[x].name << endl;
}
return 0;
}
|
And here is my output:
What is the input file name?: hosts.txt
0.0.0.0 record read
111.0.0.0 .22.3.44 platte
555.2682292.0.2682292 .66.7.88 wabash
111.1968756680.2682292.131097 .22.5.66 green
555.2683036.1968756738.0 .66.11.24 homer
123.24.0.2681224 .45.67.89 loner
12.0.9437326.2681232 .34.56.78 pizza
555.7536745.7471220.6029433 .66.9.10 ulysses
0.7209065.6029413.7929939 .0.0.0 none
7143525.4391004.7471221.6619250
7274563.7602286.7274610.5439596
4391004.7209071.7471220.7077999
7536748.5439580.7471215.6881396
5636188.7471205.6881395.7209071
0.0.0.0
So from what I can tell is that when I read the first number 111 from the hosts.txt file it stores 111 into m[0].a then 0 is filled into m[0].b , m[0].c, m[0].d. Then it reads the rest of the numbers of the ip address(not sure what they are stored into), then the string is read into the C++ string. I'm not very familiar with reading input from a txt file and storing them into arrays and structs. If anyone can give me some insight that would be great. Thanks.