2016-04-28 189 views
1

據我所知,有些函數會自動將換行符附加到它們的輸出中,但我遇到了不希望換行符的場景。我試圖解決它,並理解它爲什麼以多種方式發生,但無濟於事。這是我以前沒有經歷過的輸出問題。使用for循環,三元運算符和條件發生意外換行

我正在做一個非常基礎的項目C編程:現代方法 K.N. King,第8章,項目6:「B1FF過濾器」,其中某些字符被轉換並打印。我使用三元運算符與條件相結合來獲得適當的輸出。這裏的程序:

/* C Programming: A Modern Approach 
     Chapter 8: Arrays, Project 5: B1FF filter 
*/ 

#include <stdio.h> 
#include <string.h> 
#include <ctype.h> 

int main(void) 
{ 
    char message[50]; 
    int msg_len; 

    printf("Enter message: "); 
    fgets(message, 50, stdin); 
    msg_len = strlen(message); 

    printf("In B1FF-speak: "); 

    for (int i = 0; i < msg_len; i++) 
    { 
     message[i] = toupper(message[i]); 

     if (message[i] == 'A' || message[i] == 'B') 
      printf("%c", (message[i] == 'A') ? '4' : '8'); 

     else if (message[i] == 'E' || message[i] == 'I') 
      printf("%c", (message[i] == 'E') ? '3' : '1'); 

     else if (message[i] == 'O' || message[i] == 'S') 
      printf("%c", (message[i] == 'O') ? '0' : '5'); 

     else 
      printf("%c", message[i]); 

     if (i == (msg_len - 1)) 
     { 
      for (int j = 0; j < 10; j++) 
       printf("!"); 

      printf("\n"); 
     } 
    } 

    return 0; 
} 

預計不會輸出:

Enter message: C is rilly cool 
In B1FF-speak: C 15 R1LLY C00L 
!!!!!!!!!! 

爲什麼會出現修改字符串和感嘆號之間的換行?我清楚地指定了換行之後,在所有文本被打印之後,就在循環終止之前。我嘗試了一些改動,例如在循環外部打印一個換行符,而不是使用感嘆號等的for循環,但它會得到相同的結果。似乎沒有明確的原因。

回答

2

fgets包含在它複製到目標char緩衝區的換行符。因此,您的字符逐字符打印例程通過它不變。

結果#1 與fgets在谷歌:http://www.cplusplus.com/reference/cstdio/fgets/

一個換行符使fgets終止閱讀,但它被認爲是由功能的有效字符,其中包括複製到海峽的的字符串中。

當然,正如在其他答案中提到的那樣,您可以在打印時忽略此項,或者將其預先清空。

1

fgets()將把換行符保存到緩衝區中。如果你不想要它,請將其刪除。

例子:

fgets(message, 50, stdin); 
/* remove newline character */ 
{ 
    char* lf = strchr(message, '\n'); 
    if (lf != NULL) *lf = '\0'; 
} 

的含義是:

fgets(message, 50, stdin); /* read one line from the standard input */ 
/* remove newline character */ 
{ 
    char* lf /* declare a variable */ 
     = strchr(message, '\n'); /* and initialize it with the pointer to the first '\n' in the string message */ 
    if (lf != NULL) /* check if '\n' is found */ 
     *lf = '\0'; /* if found, replace '\n' with '\0' and delete the newline character (and string after '\n', which won't usually present) */ 
} 
+0

@underscore_d感謝您在清除了,我一定是錯過了與fgets自動添加的換行符()的函數引用。 –

+0

那麼代碼塊究竟是一步步完成的呢?它順利地完成了工作,所以非常感謝。我只想確保在使用它之前瞭解它的功能。 –

+0

@GabrielSaul我加了一些解釋。 – MikeCAT