我正在尝试实现一个简单的程序,该程序可以无限地读取用户的输入,然后将其打印出来。但是有一些问题。这是一个简单的问题,但是我的Google搜索并没有为我提供任何解决方案。这是代码。
int main() {
char pass[32];
int x=10;
while (x!=0) {
printf("\nInput the password: ");
fgets(pass, sizeof(pass), stdin);
printf("that is what i read: %s", pass);
}
return 0;
}
当我输入长度超过32个字符的字符串时,它的行为正常。
Input the password: pass
that is what i read: pass
Input the password: passsssss
that is what i read: passsssss
Input the password: passssssssssssssssssssssssssssssss
that is what i read: passsssssssssssssssssssssssssss
Input the password: that is what i read: sss
Input the password:
您在第三次尝试中看到,它将自动打印第三行。我没有输入输入'ssss'。
为什么会这样?
您将输入变量限制为32个字符,因此,为了阻止它执行此操作,只需增大pass [32]。