In: Computer Science
For example, I have an input text file that reads:
"Hello, how are you?"
"You look good today."
"Today is a great day."
How can I write a function that inputs each line into a node in a linked list? Thank you. (Note: the input text files could have a different amount of lines, and some lines could be blank.)
This is the linked list code:
#include <iostream>
#include <cstdlib>
#include <fstream>
class Node
{
public:
Node* next;
int data;
};
using namespace std;
class LinkedList
{
public:
int length;
Node* head;
LinkedList();
~LinkedList();
void add(int data);
void print();
};
LinkedList::LinkedList(){
this->length = 0;
this->head = NULL;
}
LinkedList::~LinkedList(){
std::cout << "LIST DELETED";
}
void LinkedList::add(int data){
Node* node = new Node();
node->data = data;
node->next = this->head;
this->head = node;
this->length++;
}
void LinkedList::print(){
Node* head = this->head;
int i = 1;
while(head){
std::cout << i << ": " << head->data << std::endl;
head = head->next;
i++;
}
}
int main(int argc, char const *argv[])
{
LinkedList* list = new LinkedList();
list->print();
delete list;
return 0;
}

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
class Node {
        public:
        Node* next;
        string data;
};
class LinkedList {
        public:
        int length;
        Node* head;
        LinkedList();
        ~LinkedList();
        void add(string data);
        void print();
};
LinkedList::LinkedList(){
        this->length = 0;
        this->head = NULL;
}
LinkedList::~LinkedList(){
std::cout << "LIST DELETED";
}
void LinkedList::add(string data){
        Node* node = new Node();
        node->data = data;
        node->next = this->head;
        this->head = node;
        this->length++;
}
void LinkedList::print(){
        Node* head = this->head;
        int i = 1;
        while(head){
                std::cout << i << ": " << head->data << std::endl;
                head = head->next;
                i++;
        }
}
int main(int argc, char const *argv[]) {
        ifstream f("input.txt");
        LinkedList* list = new LinkedList();
        string line;
        while(getline(f, line)) {
                if(line != "") {
                        list->add(line);
                }
        }
        list->print();
        delete list;
        return 0;
}
input.txt:
Hello, how are you?
You look good today.
Today is a great day.
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.