繁体   English   中英

混乱C开始

[英]Confusion C begining

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

在文本中,我需要使用c2c2切换c1并反向,但是当我给出a, c1c2之后启动程序时,什么也没发生。 我哪里错了?

首先, 不要使用gets() ,这本质上是危险的 ,请改用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;
   }
}
  • 不要使用gets()因为它具有不可避免的缓冲区溢出风险,在C99中已弃用,并已从C11中删除。
  • c1c2缓冲区大小不足。
  • 您应该检查读数是否成功。
  • 在进行比较以检索读取的字符之前,应先取消引用c1c2
  • else if ,则应使用else if ,否则修改后的字符将再次被修改。

尝试这个:

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

/* this is a simple implementation and the buffer for \n is wasted */
char* safer_gets(char* buf, size_t size){
  char* lf;
  if (fgets(buf, size, stdin) == NULL) return NULL;
  if ((lf = strchr(buf, '\n')) != NULL) *lf = '\0';
  return buf;
}

int main()
{
  char a[250];
  char c1[4],c2[4]; /* need at least 3 elements due to the inefficient implementation of safer_gets */
  int n,i;


  printf("Give text: ");
  if(safer_gets(a, sizeof(a)) == NULL)
  {
    fputs("read a error\n", stderr);
    return 1;
  }

  printf("Give c1: ");
  if(safer_gets(c1, sizeof(c1)) == NULL)
  {
    fputs("read c1 error\n", stderr);
    return 1;
  }
  printf("Give c2: ");
  if(safer_gets(c2, sizeof(c2)) == NULL)
  {
    fputs("read c2 error\n", stderr);
    return 1;
  }

  n=strlen(a);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM