Search code examples
c++classobjectlinked-listnodes

Having trouble converting a string to a linked character list in C++


I have been working on this for a while and am currently stumped. The starting requirement for the program is to accept a string, create an object for the class, and convert it to a linked list of characters. I'm having trouble with the whole class since when I try to predefine a new object in the Main function before the while loop I get the error charchain.cpp:(.text+0x20): undefined reference to linkedChar::linkedChar() I have tested the class and have had success with converting to a linked list of characters.

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

    struct node { 
    char data; 
    node* next; 
}; 
class linkedChar
{
    private:
    node* head;
    
    public:
    string str;
    linkedChar();
    linkedChar(const std::string s){
        head = NULL;
        strToLinkedChar(s);
    }
    

node* add(char data) 
{ 
    node* newnode = new node; 
    newnode->data = data; 
    newnode->next = NULL; 
    return newnode; 
}

node* strToLinkedChar(string str){ 
    head = add(str[0]); 
    node* curr = head; 
   
    for (int i = 1; i < str.size(); i++) { 
        curr->next = add(str[i]); 
        curr = curr->next; 
    }
     
}

void print() 
{ 
    node* curr = head; 
    while (curr != NULL) { 
        cout << curr->data << " "; 
        curr = curr->next; 
    } 
}

void listLen(){
    int counter = 0;
    node* curr = head; 
    while (curr != NULL) {
        curr = curr->next;
        counter++; 
    }
    
    std::cout << "There are " << counter << " characters in the current linked list of characters." << std::endl;
}  

};



int main()
{
    int userInput;
    linkedChar linkedObject;
    while (userInput != 6){
        userInput = -1;
        std::cout << "Option Menu: \n1. Enter new string and store as linked list of characters in an ADT LinkedChar class\n2. Get current length (number of characters stored) from the LinkedChar \n3. Find index of character in this LinkedChar \n4. Append another LinkedChar to this LinkedChar (no shallow copy)\n5. Test if another LinkedChar is submatch of this LinkedChar\n6. Quit\n" << std::endl << "Input:"; 
        std::cin >> userInput;
        std::cout << std::endl;
        if(userInput == 1){
            string str;
            std::cout << "Enter the string you want to turn into a linked list of characters: ";
            std::cin >> str;
            std::cout << std::endl;
            linkedObject = linkedChar(str);
        } else if(userInput == 2){
                linkedObject.listLen();
            }
        
    }   
}

I appreciate any input!


Solution

  • You're missing linkedChar no arguments ctor (it's declared but not defined) and you're missing return statement in strToLinkedChar.