我正在尝试用 C 语言输入字符串,并且我已经尝试了 scanf
和 fgets
来实现相同的目的。然而,发生的一件奇怪的事情是,当我在第一个字符串中输入大量内容,然后按 Enter 并输入第二个字符串时,第二个字符串会替换第一个字符串末尾的字符。 fgets
和 scanf
都会发生这种情况。我做错了什么?
这是代码
#include <stdio.h>
#include <stdlib.h>
#include <string>
#define MAX_SIZE 10000 // Added in the edit
int main() {
char* str1;
char* str2;
char* deleted;
int len1, len2;
str1 = (char*)(malloc(sizeof(MAX_SIZE)));
str2 = (char*)(malloc(sizeof(MAX_SIZE)));
deleted = (char*)(malloc(sizeof(MAX_SIZE)));
fgets (str1, MAX_SIZE, stdin);
fgets (str2, MAX_SIZE, stdin);
printf(" - %s - %d \n", str1, len1);
printf(" - %s - %d \n", str2, len2);
}
这是输出:
$ ./a.out
qwertyuiolkjhgfdsazxcvbnmSTACK
OVERFLOW
- qwertyuiolkjhgfdOVERFLOW <<<<<< The second string gets appended in the first
- 25
- OVERFLOW
- 9
最佳答案
给定#define MAX_SIZE 10000
然后
str1 = (char*)(malloc(sizeof(MAX_SIZE)));
//<-- 错误
您需要的是:
str1 = malloc(MAX_SIZE * sizeof(char));
此外,您还删除了
从未使用过的变量。
请记住,fgets
末尾有 \n
,通常使用 strcspn
删除它 ( Removing trailing newline character from fgets() input )
str1[strcspn(str1, "\n")] = 0;
最后,您使用的是完全未初始化的len1
、len2
,这导致了未定义的行为。您需要的是:
printf("- %s - %zu\n", str1, strlen(str1));
关于c - 第二个输入替换 scanf 和 fgets 中第一个输入的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827413/