c - 第二个输入替换 scanf 和 fgets 中第一个输入的最后一个字符

标签 c

我正在尝试用 C 语言输入字符串,并且我已经尝试了 scanffgets 来实现相同的目的。然而,发生的一件奇怪的事情是,当我在第一个字符串中输入大量内容,然后按 Enter 并输入第二个字符串时,第二个字符串会替换第一个字符串末尾的字符。 fgetsscanf 都会发生这种情况。我做错了什么?

这是代码

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

<小时/>

最后,您使用的是完全未初始化的len1len2,这导致了未定义的行为。您需要的是:

printf("- %s - %zu\n", str1, strlen(str1));

关于c - 第二个输入替换 scanf 和 fgets 中第一个输入的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827413/

相关文章:

c - C 中的字符串转十进制数

c - 使用 arm-none-eabi-gcc 编译 hello world 程序 C 时出错

c - 解决两个外部库中同名函数的类型冲突

c - H.264 1080p 编码

检查文件是否存在,包括在 PATH 中

c - 我是否需要在编译时添加一个 _REENTRANT 宏以使我的 errno 线程安全?

c - 为什么未排序的数组在我的代码运行时发生变化?

c - 在静态库中包含静态库依赖项的语句

C 程序,switch 语句,打印默认值和选择

c - 如何在 C 中的整数数组中选择(有效)随机相邻点?