2015-11-07 23 views
0

我有以下如何從一個字符串

An investment 
in knowledge 
pays the 
best interest 

我的代碼顯示如下字符我的代碼應該讀取該文件,並把它打印出來,某行的文本文件中刪除換行符如圖所示低於

An investment in knowledge pays the best interest 

我的代碼如下;

int main() 
{ 
    FILE *fp = fopen("C:\\Users\\abiye\\Downloads\\abiye.txt", "r"); 

    char c; 
    int d = 0; 
    char arr[200]; 

    do 
    { 
     c = fgetc(fp); 
     printf("%c",c); 
     d = d + 1; 
     if (c == '\n') { 
      putchar(' '); 

     } 


     arr[d] = c; 

    } 
    while (c != EOF); 

    fclose(fp); 
    return 0; 
    } 

而是讓我想要的結果,我得到以下印刷

An investment 
in knowledge(A space is added at the beginning of this string and the rest that follow) 
pays the 
best interest 

任何幫助,將不勝感激。

+1

@ user3121023:但是標準IO庫被迫將它翻譯成一個''\ n''。 – 3442

+0

順便說一句,如果你不想發生什麼嚴重問題,就應該擺脫'char arr [200];'和相應的'arr [d] = c;'一次,並且非常好。 – 3442

回答

3

這是因爲您在檢查之前正在打印角色。

你想要做的是檢查然後打印。

do 
{ 
    c = fgetc(fp); 
    d += 1; 
    if (c == '\n') { 
     putchar(' '); 
    } 
    else 
     putchar(c); 
    arr[d] = c; 
} 
while (c != EOF); 
+0

也許還會處理'\ r'和'\ f'和'\ t' –