Public Group

# Loops in C (si)

This topic is 2064 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

i have code and its makeing a loop even when expression is true

here is the code

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

char name[10];

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

getchar ();
getchar ();

return 0;
}
[/source]

could someone help to describeing the problem? Edited by Reenas

##### Share on other sites
Your condition is always true, you should use

 (answer != 'Y')&&(answer != 'y') 

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:

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

##### Share on other sites
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 on other sites
Thank you ! It helped!

• 19
• 10
• 19
• 14
• 20