2016-02-14 33 views
-1

我有2個C函數互相交互。第一個編寫器函數接受一個int n並且寫入「Hellohello」n次。閱讀器函數讀取輸入的內容,每50個字符插入一個換行符。作家插入不需要的換行符

我目前的困境是,當我有大量的字符數是50時,我的讀者在我不想要的時候會插入一個額外的換行符。我已經嘗試了多種不同的方法來解決這個問題,而我嘗試過的任何方法都尚未解決。我提供的是我的閱讀器代碼,沒有任何我嘗試修復的問題,也是一個問題的例子。

我不得不使用getchar和putchar,我明白如果我不使用它們,會有更簡單的方法,但不幸的是它是必須的。對於我應該如何處理這件事或任何我應該考慮過的事情的任何幫助都非常感激。

讀者代碼:

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int count = 0; 
    char c; 
    while (c != EOF) 
    { 
    c = getchar(); 
    if (count == 50) 
    { 
     putchar('\n'); 
     count = 0; 
    } 
    putchar(c); 
    count++; 
    } 
} 

輸出示例:

[88] [[email protected]:~/csc412]$ writer 10 | reader1 
HellohelloHellohelloHellohelloHellohelloHellohello 
HellohelloHellohelloHellohelloHellohelloHellohello 

▒[89] [[email protected]:~/csc412]$ 

編輯:清晰

回答

0

只需更改正在檢查計數的if語句以包含對換行符的檢查。這解決了發生的問題。

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int count = 0; 
    char c; 
    while (c != EOF) 
    { 
    c = getchar(); 
    if ((count == 50) && (c != '\n')) 
    { 
     putchar('\n'); 
     count = 0; 
    } 
    putchar(c); 
    count++; 
    } 
} 
1

當你閱讀(getchar函數)打印一個換行符(的putchar)一個換行符。

此外,'c'應該被聲明爲'int'',所以它足夠大以保持EOF正確。

而且「C」的價值是不確定的,通過循環的第一時間和您打印「EOF'」,使用:

while ((c = getchar()) != EOF) { … 

此外,你應該使用int main (void) { …

與C語言確實有「班級」,只有功能。