C程序无限期循环 [英] C program loops indefinitely
本文介绍了C程序无限期循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行我的程序,它要求无限的密码。我输入正确的密码,但它只是循环回来。有没有错误,而我是编译。要编译,我用:
When I run my program it asks for the password indefinitely. I enter the correct password but it simply loops back. There were no errors while I was compiling. To compile, I used:
gcc -ansi -W -Wall -pedantic -o prog myProgram.c
chmod +x prog
我运行Ubuntu信赖。下面是相关的密码code:
I am running ubuntu trusty. Here is the code related to the password:
char string[100] = "";
int main(void)
{
char correctPassword[25] = "myPassword";
char password[25] = "";
system("clear");
printf("Enter your password:\n");
scanf("%s", password);
if (password == correctPassword)
{
system("clear");
printf("Enter a string:\n");
scanf("%s", string);
}
else
{
system("clear");
printf("Sorry, incorrect password\n");
system("pause");
main();
}
更新code:
char string[100] = "";
int main(void)
{
char correctPassword[25] = "myPassword";
char password[25] = "";
int ret;
system("clear");
printf("Enter your password:\n");
scanf("%s", password);
ret = strcmp(password, correctPassword);
if (ret == 0)
{
system("clear");
printf("Enter a string:\n");
scanf("%s", string);
}
else
{
system("clear");
printf("Sorry, incorrect password\n");
system("pause");
main();
}
return 0;
}
编辑2:我认为这是超越现在解决了,我怎么把它标记为这样
edit 2: i think this is beyond solved now, how do i mark it as such?
推荐答案
这行
if (password == correctPassword)
没有做什么,你认为它。它不是比较字符串,它是在比较每个字符串的第一个字符的存储器地址。如果要比较的字符串,你要使用的strcmp,你可以读到这里: HTTP: //www.tutorialspoint.com/ansi_c/c_strcmp.htm
修改为了应对在code修改;你有行
EDIT In response to the change in the code; you have the line
if(ret = 0)
您想
if(ret == 0)
我假设这是一个错字。
I'm assuming this is a typo.
这篇关于C程序无限期循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文