gpt4 book ai didi

迷惑C开头

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:13 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h>


int main()
{
char a[250];
char c1[1],c2[1];
int n,i;


printf("Give text: ");
gets(a);

printf("Give c1: ");
gets(c1);
printf("Give c2: ");
gets(c2);

n=strlen(a);

for(i=0;i<n;i++)
{
if(a[i]==c1)
{
a[i]=c2;
}
if(a[i]==c2)
{
a[i]=c1;
}
}
printf("%s",a);
return 0;
}

在文本中,我需要将 c1 切换为 c2 并反转,但是当我在给出 a、c1c2 后启动程序时,什么也没有发生。我哪里错了?

最佳答案

首先,don't use gets(), it's inherently dangerous , 使用 fgets()相反。

最重要的是,当您使用 gets(c1) 时,c1 是一个单元素数组,您已经超出了调用 undefined behavior 的已分配内存。 .

就是说,您将 c1c2 作为单元素数组,这并没有错,但也不是必需的。将它们定义为简单的 char 变量

char c1;
char c2;

像这样使用它们

 scanf(" %c", &c1);  // mind the space and don't forget to to check the return 
scanf(" %c", &c2); // value of scanf() to ensure proper scanning.

之后,a[i] == c2 的检查应该作为 else 构造,否则,您将覆盖之前的操作。有点像

for(i=0;i<n;i++)
{
if(a[i]==c1)
{
a[i]=c2;
}
else if(a[i]==c2)
{
a[i]=c1;
}
}

关于迷惑C开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37632429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com