[英]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()
時會出現問題。
下面的代碼將為您服務。 在執行任何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.