【问题标题】:Using strtok() to add elements to an array but the last element gets messed up使用 strtok() 将元素添加到数组但最后一个元素搞砸了
【发布时间】:2022-11-21 03:11:08
【问题描述】:

我正在处理的程序的第一部分接受用户输入(使用 read() ),并使用 strtok() 将每个由空格分隔的单词存储到数组中。但是,当用户输入他们的字符串时,他们必须按“enter”才能真正提交字符串。下面的代码显示 strtok 从设置的字符串而不是用户输入中读取,但它准确读取字符串的内容,末尾有“\n”。我该如何消除“\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]);
    }
}

我试图在字符串的末尾添加和 EOF 但我没有成功

【问题讨论】:

  • 例如写 while ((token1 = strtok_r(rest, " \n", &rest))) 就足够了 或者最好写 while ((token1 = strtok_r(rest, " \t\n", &rest) ))
  • 只需查看中的最后一个字符,但它是 \ 并替换为 \0

标签: arrays c newline strtok


【解决方案1】:

对于初学者,您可以通过以下方式删除尾随的换行符' '

buf[ strcspn( buf, "
" ) ] = '
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2017-05-09
  • 2021-04-22
  • 1970-01-01
  • 2016-12-24
  • 2022-01-23
  • 2019-08-19
相关资源
最近更新 更多