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

Time:11-21

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

CodePudding user response:

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)
  • Related