Question

I am trying to read in a text file that has a name and age on each line such as this

Tom
55
Bob
12
Tim
66

I then need to pass it to a function which takes in a string and an int such as:

sortDLL.Insert(name, age);

However, I am unsure how to do this. I tested it out with the following and it works (bypassing the text file):

string tom = "tom";
string bob = "bob";
string tim = "tim";
int a = 55;
int b = 12;
int c = 66;

     sortDLL.Insert(tom, a);
     sortDLL.Insert(bob, b);
     sortDLL.Insert(tim, c);

But when I try to read in the text file and send it, the program doesn't run properly. This is what I am currently trying, and I have messed around with a few other things, but have had no luck:

ifstream infile ("names.txt");


while(getline(infile, line));
{
    istringstream ss(line);
    if (ss >> name)
        cin >> name;
    else if (ss >> wt)
        cin >> wt;

    sortDLL.Insert(name, wt);


}
infile.close();

Like always, any help to get this to work would be greatly appreciated, thanks!

Was it helpful?

Solution

I think the correct code should look like this. Remember you have to read 2 line per 1 insert.

while(getline(infile, line))
{
    stringstream ss(line);

    ss >> wt;
    if(ss.fail()) {
        name = line;
        continue;
    }
    else {
        // cout << name << ":" << wt << endl;
        sortDLL.Insert(name, wt);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top