我正在處理的程式的第一部分接受用戶輸入(使用 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 但我沒有成功
uj5u.com熱心網友回復:
'\n'對于初學者,您可以通過以下方式洗掉尾隨的換行符
buf[ strcspn( buf, "\n" ) ] = '\0';
另一種方法是撰寫strtok_r例如以下方式的呼叫
strtok_r(rest, " \t\n", &rest)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/536604.html
標籤:数组C新队strtok
