[英]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: 要对此发表评论:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.