程序反转c中的字符串,但它在/0位置打印a

  • 本文关键字:位置 打印 字符串 程序 c
  • 更新时间 :
  • 英文 :


程序如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
setbuf(stdout,NULL);
int l,i;
char s[10],c;
printf("Enter the string: ");
gets(s);
l=strlen(s);
for(i=0;i<l/2;i++){
c=s[i];
s[i]=s[l-1-i];
s[l-1-i]=c;
}
printf("The reversed string is: %s ",s);
return EXIT_SUCCESS;

}

输出为:输入字符串:helloworld。反向字符串为:hlrow olleo。

首先,正如@Passerby所提到的,不应该再使用gets函数。相反,您可以使用fgets((函数来获取输入。

fgets(s, sizeof(s), stdin);  // read string

其次,您将输入存储在大小为10的数组中,而输入字符串的长度为11。因此,"world"的"d"根本没有读出来。将数组大小更改为更大的值,并将gets替换为fgets,问题就会得到解决。

char s[15], c;

只需尝试增加字符数组的大小bcoz输入字符串的大小"你好世界";大于10或尝试插入类似"0"的小字符串;嗨世界";

最新更新