【发布时间】: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