c - 在 C 中查找字符串长度的问题

标签 c string

这是代码

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
  clrscr();
  char a[20],rev[20];
  printf("enter the string");
  scanf("%s",a);
  int len=strlen(a);
  for(int i=0;i<len;i++)
  {
    rev[i]+=a[len-i-1];
  }
  printf("%d \t  \n string is \t %s",len,rev);
  getch();
}

当我们给它一个没有空格的字符串时它可以正常工作:

input: welcome
len:7
output: emoclew

当我们给它一个带空格的字符串时:

input : welcome to this world
len:7
output:some other ascii chars that I have not seen so far. and the "len" is again 7 only

当我更改以下语句时:

scanf("%s",a) to gets(a);

我得到:

input :welcome to this world
len:21
output : something different. not the reverse of string...

在这种情况下,“len”是正确的,但输出是错误的。

到底发生了什么?上面的代码有什么问题?

最佳答案

scanf 不会读取整行。相反,它会读到第一个空格...您需要 getline

另外,我注意到你有长度超过 19 的东西,但你分配了 20 个字符的空间。增加它或者你得到 UB

关于c - 在 C 中查找字符串长度的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6482990/

相关文章:

c++ - 为什么C++语言的malloc函数前面要写指针类型?

java - FindClass ("..","[I") 是做什么的?

c - 如何在 gdb 中使用数学函数

c++ - 为什么不能像这样复制 char 数组 charArray ="some string";

c++ - vector <unsigned char> 与二进制数据的字符串

Python3 : Iterating a binary string turns character into integer

java - 在 ArrayList 中使用二分搜索查找具有给定前缀的单词

c - 在很小的内存中表示非常大的位数组

c - for 循环比较中什么更快?

java - StringBuffer类与汉字编码