我在这里编写了一个脚本,但在执行do-while循环时遇到了麻烦。我可以使它无限运行(继续)或仅运行一次(中断)。我所设定的条件可能有问题...我在这里很茫然,因此任何帮助将不胜感激
#include <stdio.h>
#include <time.h>
int main ()
{
int age;
char string[50];
char string2[4];
int yearsleft;
/*
FILE *fp;
fp = fopen( "RetireeFileForCo.txt", "a+" );
*/
do {
printf( "What is your name? \n");
scanf( "%s", string );
printf( "Hello %s\n", string );
printf ("What is your age? \n");
scanf ("%d", &age);
printf ("You enter %d\n", age );
if ( age > 65 ) {
printf (".... You should already be retired %s\n", string );
// fputs ( ".... You should already be retired %s\n", fp, string );
} else {
yearsleft = 65 - age ;
printf ("Your number of years left until retirement is %d\n", yearsleft);
}
/*
fputs ( "As of the date above.... You should already be retired %s\n", fp );}}
fclose (fp);
*/
printf( "Do you want to check another person's status? (yes or no) \n");
scanf( "%s", string2 );
if("string2 = yes") {
continue;
}
printf ("Thank you for your input\n");
}
while("string2 = yes");
return 0;
}
答案 0 :(得分:5)
语句if ( "string2 = yes" )
和while ( "string2 = yes" )
确实是问题所在。 "string2 = yes"
只是一个字符串,在如上所述的布尔上下文中,其值为true
(或更准确地说,为not false
)。
要比较字符串值,必须使用库函数strcmp
(没有为字符串或任何其他数组表达式定义=
赋值或==
比较运算符):>
if ( strcmp( string2, "yes" ) == 0 ) // strcmp returns 0 if the arguments are equal
{
// do something if string2 is equal to yes
}
do
{
// loop at least once, repeat if string2 is equal to "yes"
} while( strcmp( string2, "yes" ) == 0 );
您也可以将它们写为if ( !strcmp( string2, "yes" ) )
和while ( !strcmp( string2, "yes" ) )
。