Hello I have this problem where my text file is not read in properly to the linked list. It spits out only zeroes. Here is the code I have written. Thanks.

include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;

    struct widget
    {
    double R;
    double S;
    int P;
    widget* next;
    };

widget* temp = new widget;
widget* head_ptr = temp;
void widger();
int main()
{
string line;
ifstream inFile("data.txt");
if(inFile.is_open()){
while (inFile.good())
{
getline (inFile, line);
inFile >> temp->R;
inFile >> temp->S;
inFile >> temp->P;
temp->next = new widget;
temp = temp->next;

cout<< setw(25)<< temp->R << endl;
cout<< setw(25)<< temp->S << endl;
cout<<setw(25) << temp->P << endl;
}
temp->next == NULL;

}

inFile.close();


return 0;
}
    void widger(widget* head_ptr)
    {
    widget* node = head_ptr;
    widget* temp = NULL;
    while(node->next != NULL)
    {
    if(node->R > node->next->R)
    {
    temp = node->next;
    node->next = temp->next;
    temp->next = node;
    }
    node = node->next;

    }
    }

Is there a specific reason why want to use linked lists? A std::vector<Widget> would be a lot easier to use.

You are moving the temp to temp next before and then trying to print temp's variables! That's why you're getting all garbage!

You should move line# 29 and 30 between line# 34 and 35.

But that's not the only problem!
You're reading off the first line using getline! The inFile >> temp->R etc. assignments are only assigning from 2nd line onwards, if at all there is a 2nd line!

Even if you remove the getline (which you should) your loop needs a check for EOF and when it happens it should break out. Otherwise, your code will fail for empty files and for a file with 2 lines it will print garbage for the 3rd iteration.
You should have something like if ( inFile.eof()) break; between line# 28 and 29.

And for all the above reasons its perhaps better to use a std::vector<Widget> as Nick suggested.

Thanks for the help. Makes a lot of sense. This is for a class assignment so I must use linked lists.

No luck yet still getting garbage.

share your modified code...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.