简体   繁体   English

在C中查找字符串长度时出现问题

[英]Problem finding the string length in C

Here is the code 这是代码

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

It was correctly working when we gave it a string without spaces: 当我们给它一个没有空格的字符串时,它可以正常工作:

input: welcome 输入:欢迎
len:7 len:7
output: emoclew 输出:emoclew

When we give it a string with a space: 当我们给它一个带空格的字符串时:

input : welcome to this world 输入:欢迎来到这个世界
len:7 len:7
output:some other ascii chars that I have not seen so far. 输出:到目前为止尚未见过的其他ascii字符。 and the "len" is again 7 only 而“ len”又是7

When I change the following statement: 当我更改以下语句时:

scanf("%s",a) to gets(a); scanf(“%s”,a)到gets(a);

I get: 我得到:

input :welcome to this world 输入:欢迎来到这个世界
len:21 len:21
output : something different. 输出:有所不同。 not the reverse of string... 不是字符串的反向...

In this case "len" is correct but the output is wrong. 在这种情况下,“ len”是正确的,但输出是错误的。

What is really happening? 到底发生了什么事? What is the problem with the above code? 上面的代码有什么问题?

scanf will not read the entire line. scanf不会读取整行。 Instead it'll read up to the first space... You need getline 相反,它会读到第一个空格...您需要getline

Also, I notice you have things with length more than 19 but you allocated space with for 20 chars. 另外,我注意到您的东西长度超过19,但是您为20个字符分配了空间。 Increase that or you get UB 增加或您得到UB

In addition to what others have said, rev is not guaranteed to be initialized to NUL characters, so your rev[i]+=a[len-i-1]; 除了其他人所说的, rev不能保证被初始化为NUL字符,因此您的rev[i]+=a[len-i-1]; line can end up with garbage. 线最终可能会产生垃圾。

Use the following: 使用以下内容:

scanf("%[^\\t\\n]",string); scanf(“%[^ \\ t \\ n]”,string);

To comments on it: 要对此发表评论:

  1. As Armen Tsirunyan wrote, you probably want getline 正如Armen Tsirunyan所写,您可能需要getline
  2. You only have a character array of size 20 - so passing a bigger string will occur in a buffer overflow (which makes your program very insecure - google for buffer overflow attack if you want to know more about it) - this is why you should make sure that you never read more than the size of your character array... 您只有一个大小为20的字符数组-因此在缓冲区溢出中将传递较大的字符串(这会使您的程序非常不安全-如果您想了解更多信息,请使用google进行缓冲区溢出攻击)-这就是为什么您应该确保您读的字永远不会超过字符数组的大小...

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

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