[英]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.