簡體   English   中英

使用strcat的錯誤字符串連接

[英]Wrong string concatenation using 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

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

PS我認為當我使用函數fgets()時會出現問題。

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

fgets()讀取並存儲結尾的換行符( \\n )。 您需要先刪除(剝離)存儲輸入的內容。

也就是說,請注意:

  1. 當您定義了固定大小的緩沖區時,請不要無限增大i 可能溢出。

  2. 確保您的buff[i]足夠大,可以容納串聯的字符串。 否則,它將調用未定義的行為

下面的代碼將為您服務。 在執行任何String操作之前,您需要添加Null字符 無論我在哪里修改,我都會注釋代碼。

#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;
}

暫無
暫無

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

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