put integers from txt file to linked list

i have a code where i count the numbers of integers in txt file (there is a million integers)
now i want to copy these integers into the linked list for further operations. how can i do that?
#include <iostream>
#include <fstream>
#include <stdlib.h> // for exit(1) in the code below
#include <ctime>

using namespace std;

int main(){
size_t sz = 0; // total num of integers
int line;
fstream file;
file.open("numbers.txt");

if(file.fail()){
cerr << "Error opening the file" << endl;
exit(1); // closing application without any crashing
}

while(file >> line){
++sz;
}
cout << "There is totally " << sz << " numbers in the text file" << endl;
cout << "============" << endl;


file.close();
return 0;
}


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
#include<iostream>
#include<fstream>
using namespace std;

struct Node
{
    int m_num;
    Node* m_next;

    Node (int num) : m_num(num){};
    void setNext(Node* next) {m_next = next;}
    void print()const
    {
        cout << m_num << " ";
        if(m_next != nullptr)
        {
            m_next -> print();
        }
    }
};

int main()
{
    ifstream infile("D:\\input.txt");

    Node* head = nullptr;
    int num;
    while(infile)
    {
        infile >> num;
        if(infile)
        {
            Node* temp = new Node(num);
            temp ->setNext(head);
            head = temp;
            delete temp;
        }
    }
    if(head != nullptr)
    {
        head -> print();
    }
}

Sample .txt file 1 2 3 4 5 5 6 7 8 9

Output
1
2
3
9 8 7 6 5 5 4 3 2 1
Process returned 0 (0x0)   execution time : 0.125 s
Press any key to continue.


Last edited on
Topic archived. No new replies allowed.