lista jednokierunkowa, odczytywanie z pliku

0
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
using namespace std;

struct student {
	int nr_indeksu;
	int nazwisko;
	int ocena;
	struct student *nast;
};


int main()
{	int a;
	struct student *wsk = NULL;
   struct student *glowa = NULL;
	 FILE *stream = fopen("dane.txt", "r");
    if (stream == NULL)
    {
        cout<<"Nie udalo sie otworzyc pliku notatki.txt";
        return 1;
    }
    cout<<"Plik otwarty pomyslnie!";

		while (!feof( stream )) {
		if (glowa == NULL)
			glowa = wsk = (struct student*)malloc(sizeof(struct student));
				else {
				wsk->nast = (struct student*)malloc(sizeof(struct student));
				wsk = wsk->nast;
				}
			fscanf(stream, "%s %s %s\n", wsk->nr_indeksu,wsk->nazwisko,wsk->ocena);
			wsk->nast = NULL;
			}
			fclose(stream);

	return 0;
} 

Do oczytanie mam dane z pliku, natomiast to co napisałem nie działa. Jakieś sugestie?

0

Jakieś sugestie?

Wszystko wywalić i napisać od nowa. Przeczytaj może wcześniej jak się robi takie listy prawidłowo, bo to co robisz tutaj w main nie ma sensu. Poza tym mieszanie kodu C z C++ też jest tutaj bez sensu. Skoro to C++ to używaj new zamiast malloc'a i <fstream> zamiast FILE etc..

Zrób np. coś takiego:

#include<iostream>
using namespace std;

template<class T>
class LinkedList {
private:
    struct Node {
        T value;
        Node *next;
        Node(const T& value) : value(value), next(nullptr) {}
    };

    Node *root;

public:
    LinkedList() : root(nullptr) {}
    ~LinkedList(){
        while(this->root){
            Node* current = this->root->next;
            delete this->root;
            this->root = current;
        }
    }

    void add(const T& value) {
        Node *newNode = new Node(value);
        newNode->next = this->root;
        this->root = newNode;
    }

    void print(void(*printAction)(const T& value)) {
        Node* temp = this->root;
        while (temp) {
            printAction(temp->value);
            temp = temp->next;
        }
    }
};

void printInt(const int& number) { cout << number << endl; }

int main() {
    LinkedList<int> list;
    for (int i = 0; i < 10; ++i) list.add(i);
    list.print(printInt);
    return 0;
}

I dopnij do tego obsługę plików i będzie w porządku.

1 użytkowników online, w tym zalogowanych: 0, gości: 1