Sign in to follow this  
Reenas

Loops in C (si)

Recommended Posts

Reenas    124
i have code and it`s makeing a loop even when expression is true

here is the code

[source lang="plain"]
int main (){

char name[10];
char answer ;


do
{
printf ("Chouse your Username\n");
scanf ("%s" , &name);
printf ("U chouse %s.\n Do you want to leave it? (Y/N)" , &name);
scanf ("%s", &answer);
}

while ((answer != 'Y')||(answer != 'y')) ;

getchar ();
getchar ();

return 0;
}
[/source]


could someone help to describeing the problem? Edited by Reenas

Share this post


Link to post
Share on other sites
rnlf_in_space    1894
Your condition is always true, you should use

[CODE]
(answer != 'Y')&&(answer != 'y')
[/CODE]

In your case, if answer is 'y', the answer!='Y' term will be true, if the answer is 'Y', the answer!='y' term will be true, thus the overall result is always true.

Also, %s in scanf works only for strings, since you don't have a string, but only one single character, you do actually have a buffer overflow here (because scanf will ALWAYS write at least one byte too much (the terminating 0-byte). If you enter more than 1 character, you will actually overwrite a whole lot more of memory, not a good thing to do. The same goes for your name string, if you enter 10 or more characters, you produce a buffer overflow.

You can solve this problem by specifying the size of your string in the scanf format string:

[CODE]
char name[10];
char answer[2];
scanf("%9s", name);
scanf("%1s", answer);
OR:
char answer;
scanf("%c", &answer);

[/CODE] Edited by rnlf

Share this post


Link to post
Share on other sites
Bacterius    13165
[source lang="c"]while ((answer != 'Y')||(answer != 'y')) ;[/source]
Bad logic here. You're saying: continue looping until the user inputs something else than 'Y' OR something else than 'y', which is always true by definition, since at least one of them has to be true if the other is not. Use && instead.

EDIT: haha, ninja'ed! +1 rnlf. Edited by Bacterius

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this