簡體   English   中英

如何用C中的換行符解析字符串?

[英]How do I parse strings with the newline character in C?

我正在寫一個shell,我正在使用getline()和鍵盤中的stdin來接受命令。 我雖然難以對輸入進行標記。 我嘗試在strtok()函數中使用\\ n作為分隔符,但似乎沒有工作。

例如,我包含一個if語句來檢查用戶是否鍵入“exit”,在這種情況下它將終止程序。 它沒有終止。

這是我正在使用的代碼:

void main() {
int ShInUse = 1;
char *UserCommand;   // This holds the input
int combytes = 100;
UserCommand = (char *) malloc (combytes);
char *tok;

while (ShInUse == 1) {
   printf("GASh: ");   // print prompt
   getline(&UserCommand, &combytes, stdin);
   tok = strtok(UserCommand, "\n");
   printf("%s\n", tok);

   if(tok == "exit") {
      ShInUse = 0;
      printf("Exiting.\n");
      exit(0);
   }
}
if (tok == "exit")

tokexit是指針,所以你要比較兩個指針。 這會導致未定義的行為,因為它們不屬於同一個聚合。

這不是比較字符串的方法。 使用相當strcmp

 if (strcmp (tok, "exit") == 0)

正如@Kirilenko所說,你不能使用==運算符來比較字符串。

但那不是它。 如果您正在使用getline() ,則無需將輸入拆分為行,因為getline()只讀取一行。 如果你確實想要將輸入拆分為其他分隔符,你可以在循環中調用strtok()直到它返回NULL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM