当我包含 scanf 来读取字符串时,n 的值在下面的代码中突然改变。我也试过 %*c 但它仍然显示相同的错误。
#include<stdio.h>
#include<string.h>
int main()
{
char str[3];
int n;
int t,p=0;
scanf("%d",&t);
while(t--)
{
printf("t=%d ",t);
scanf("%d",&n);
while(n!=0)
{
printf("n=%d",n);
p=0;
scanf("%s",str);
getchar();
if(strcmp(str,"lhx")==0)
printf("lhx");
else
printf("hhb");
n--;
}
}
return 0;
}
最佳答案
根据 if(strcmp(str,"lhx")==0)
判断,您输入了 3 个字符。但是 str
的内存只有 3
个字符。要将其扫描为 string,str
至少需要 4 个字节的内存。
您可以通过将其更改为:
char str[4];
但是话又说回来,当你输入 4 个字符时,你会遇到同样的问题。使用 fgets
而不是 scanf()。
fgets()
将防止缓冲区溢出。
另外:为 main()
使用标准签名:int main(void)
或 int main(int argc, char**argv)
或等效代码。
关于c - 使用 scanf 读取字符串的 while 循环变量的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30954366/