开发者

Problem finding the string length in C

开发者 https://www.devze.com 2023-03-15 05:57 出处:网络
Here is the code #include<stdio.h> #include<conio.h> #include<string.h> void main() { clrscr();

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

output: emoclew

When we give it a string with a space:

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

When I change the following statement:

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

I get:

input :welcome to this world

len:21

output : something different. n开发者_开发知识库ot the reverse of string...

In this case "len" is correct but the output is wrong.

What is really happening? What is the problem with the above code?


scanf will not read the entire line. Instead it'll read up to the first space... You need getline

Also, I notice you have things with length more than 19 but you allocated space with for 20 chars. Increase that or you get 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]; line can end up with garbage.


Use the following:

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


To comments on it:

  1. As Armen Tsirunyan wrote, you probably want 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...
0

精彩评论

暂无评论...
验证码 换一张
取 消