1

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
sgrandom
  • 27
  • 3
  • It is enough to write for example while ((token1 = strtok_r(rest, " \n", &rest))) Or it will be better to write while ((token1 = strtok_r(rest, " \t\n", &rest))) – Vlad from Moscow Nov 20 '22 at 18:31
  • simply look at the last char in buf, its its \n replace with \0 – pm100 Nov 20 '22 at 18:33
  • Possible duplicate: [Removing trailing newline character from fgets() input](https://stackoverflow.com/q/2693776/12149471) – Andreas Wenzel Nov 20 '22 at 18:41

1 Answers1

1

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)
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335