2015-06-05 28 views
0

我正在寫一個程序,它從文件中讀取字符串,將它們保存到'字符串緩衝區',然後連接這些字符串並將它們寫入另一個文件。使用strcat錯誤的字符串連接

#define _CRT_SECURE_NO_WARNINGS 
#include <cstdlib> 
#include <iostream> 
#include <string.h> 
#include <stdio.h> 

int main() { 
    FILE *f = fopen("Read.txt", "r"); 
    char line[20]; 
    char buff[15][20]; 
    int i = 0; 
    while (fgets(line, 18, f)) { 
     strcpy(buff[i], line); 
     i++; 
    } 
    FILE *h = fopen("Out.txt", "w+"); 
    for (int j = 0; j < i; ++j) { 
     char ct[4] = "smt"; 
     strcat(buff[j], ct); 
     fputs(buff[j], h); 
    } 
    return 0; 
} 

文件Read.txt的內容:

Lorem ipsum 
dolor sit 
amet 

預期輸出(文件Out.txt):

Lorem ipsumsmt 
dolor sitsmt 
ametsmt 

但我得到Out.txt:

Lorem ipsum 
smtdolor sit 
smtamet 
smt 

那麼如何獲得預期的結果呢?

P.S.我認爲當我使用功能fgets()時會出現問題。

回答

5

這不是一個錯誤或問題,而是一個預期的行爲。請繼續閱讀。

fgets()讀取並存儲尾隨換行符(\n)。您需要在存儲輸入之前移除(剝離)。

不過,請注意:

  1. 請不要讓當你已經定義了一個固定大小的緩衝區的i無限的增量。可能溢出。

  2. 確保您的buff[i]足夠大以容納連接的字符串。否則,它將調用undefined behaviour

+0

好吧,那麼你能解釋如何刪除尾隨的換行符嗎? – k1ber

+0

但是我並不持有連接字符串,我把它保存在buff [i] – k1ber

+0

@KiberPrestupnik有許多方法,我更喜歡單行,'line [strchr(line,'\ n')-1] = 0;'或類似的東西沿線。 –

1

以下代碼適用於您。在執行任何字符串操作之前,您需要添加Null Character。無論我在哪裏修改,我都會對代碼進行評論。

#define _CRT_SECURE_NO_WARNINGS 
#include <cstdlib> 
#include <iostream> 
#include <string.h> 
#include <stdio.h> 

int main() { 
    FILE *f = fopen("Amol.txt", "r"); 
    char line[20]; 
    char buff[15][20]; 
    int i = 0; 
    while (fgets(line, 18, f)) { 
     line[strlen(line) -1] = '\0'; // Here I added NULL character 
     strcpy(buff[i], line); 
     i++; 
    } 
    FILE *h = fopen("Out.txt", "w+"); 
    for (int j = 0; j < i; ++j) {  
     char ct[5] = "smt\n";  // As \n will be at the end,so changed this array 
     strcat(buff[j], ct);   
     fputs(buff[j], h); 
    } 
    return 0; 
}