Question

I'm having a problem with cin in c++. I'm trying to cin a text file to the program, and then put all the words etc. in a linked list, but I'm having a problem with the temp->next part, the core gets dumped.

string x = ""; //ordet blir lagret her
string y = stopwords_c;
string tegnfjern = stopchars_c;

int antallOrd = 0;

struct ord{
string ordet;
int ant;
};

struct node{
node* next;
ord o;
};

int main(){

    node* ord = new node;
    node* temp = ord;


while(cin >> x)
{
    if(temp == NULL)
    {
        temp->o.ant++;
        temp->o.ordet =x;
        antallOrd++;
    }

    else
    {
        while(temp->next != NULL && temp->o.ordet != x)
        {
            temp = temp->next;
        }

        if(temp->o.ordet == x)
        {
            temp->o.ant++;
        }

        else
        {
            if (cin >> x)
            {
                temp->next = new node;
                temp = temp->next;
            }

            temp->o.ordet = x;
            temp->o.ant++;
        }

        temp = ord;                
    }
}

No correct solution

OTHER TIPS

You first check if if(temp == NULL) and if it is so you nevertheless want to access members of it. That cannot work. If temp is NULL you have to create new node struct and add it to the list (depending on what temp exactly represents). So some more information about the node structure and the list would be great.

EDIT Let me summarize what you should do:

  • Add default constructors to both structs that initialize ant to 0 and next to NULL (or nullptr if you can use the new standard).
  • As already mentioned several times: get rid of the code that tries to access members of a nullptr.
  • Just drop the if (cin >> x). You don't need it as you ignore the old value that was read into x in the loop condition (and furthermore if cin >> x fails you overwrite an existing entry). But only the condition itself - not the code executed inside it: you definitly need that code as it creates the new node to store the new word. Draw a picture with boxes and arrows if you don't know how that could happen.

If you do all that it should work - at least it then worked for me. Furthermore:

  • I hope you know that there is some kind of sentinal in this list: the element created with node* ord = new node; always remains in the list and counts all occurences of the string "". You must pay attention to that (especially when freeing the elements in the list).
  • I would merge both structs into one single struct as it makes the code more readable (at least in my opinion).
  • Don't forget to free your list properly!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top