Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using strtok() to add elements to an array but the last element gets messed up

The first part of a program im working on takes the user input (using read() ), and uses strtok() to store each word seperated by a space into an array. However, when the user enters in their string, they must press "enter" to actually submit the string. The code below shows strtok reading from a set string and not from the user input, but it is reading exactly what the string says, with the "\n" at the end. How do i go about eliminating the "\n"?

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>


int main()
{
    int n;
    printf("Please enter commands: \n");
    char buf[] = "wc file1.txt file2.txt\n";

    int i = 0;
    char* array[100];
    char* token1;
    char* rest = buf;

    while ((token1 = strtok_r(rest, " ", &rest)))
    {
        printf("%s:\n", token1);
        array[i++] = token1;
        
    }

    for (int j = 0; j < i; j++)
    {
        //array[j] = token1;
        //token1 = strtok(NULL, " ");
        printf("Array value %d: %s:\n", j, array[j]);
    }
}

I’ve tried to just add and EOF at the end of the string but i didn’t have any success with that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For starters you can remove the trailing new line character '\n' the following way

buf[ strcspn( buf, "\n" ) ] = '\0';

Another approach is to write the call of strtok_r for example the following way

strtok_r(rest, " \t\n", &rest)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading