Home > other >  How to Read in a String With Spaces into a Linked List?
How to Read in a String With Spaces into a Linked List?

Time:11-07

So essentially I am reading data into this linked list, then after each node is inserted (front or back) I display the nodes. When I do this, everything works fine with names without spaces, but if I use first and last with a space it does not function properly and will separate the string(s) with spaces into 2 different nodes, usually opposite of each other. Here is my code to read the data that is entered:

    struct node *new_node() {
    
        struct node *new1=(struct node *)malloc(sizeof(struct node));
    
        cin >> new1 -> string_val;
        new1 -> next=NULL;
    
        return new1;
    }

The constructor for the struct 'node' is as follows:

        struct node {
            char string_val[20];
            struct node *next;
        };
    

CodePudding user response:

Assuming the node definition needs to be the same and input is through stdin and all one one line for the following answer. Due to use of char [20] input from stdin is truncated to prevent overflow or segfault.

Given the following node (preserving OP's node definition):

struct node {
    char string_val[20];
    struct node *next;
};

Node can be constructed with following:

struct node *new_node() {
    // Create new node
    node * newNode = new node;

    // Get line
    std::cin.getline(newNode->string_val, 20);

    // Set next node to nullptr
    newNode->next = nullptr;

    return newNode;
}

If node definition can be changed and std::string can be used then this changes to the following:

#include <string>

struct node {
    std::string string_val;
    struct node *next;
};

struct node *new_node() {
    // Create new node
    struct node * newNode = new node;

    // Get line
    std::getline(std::cin, newNode->string_val);

    newNode->next = nullptr;

    return newNode;
}
  • Related