char str[6];
do
{
printf("Enter the string you wanna check:");
scanf("%s", str);
}
while(str != "exit");
Why does this not work?
char str[6];
do
{
printf("Enter the string you wanna check:");
scanf("%s", str);
}
while(str != "exit");
Why does this not work?
str
will never equal "exit"
, because you're comparing the addresses of two different sections of memory. You probably want to compare the contents of the strings, for which there is a function strcmp()
.
"exit"
is a char[5]
generated by the compiler at some address in the data segment. This address is definitely different from the address of str
, as two different objects cannot occupy the same location in memory.
The !=
operator between expressions of type char[]
compares two pointers. These two pointers are the address of "exit"
and the address of str
, which, as I have already explained, will never be equal.
So, the expression str != "exit"
will never evaluate to true
. Which brings us to another point: your compiler should have issued a warning about this condition being always false. Which means that you are trying to program without -Wall
. Don't do this, you are never going to get very far. Always use the highest warning level, and when you see warnings, always fix them.
To correct the problem, do as user3121023 suggested in a comment, and use strcmp()
to compare strings.
The short answer is: it does not work because you must use strcmp(str, "exit")
to compare the strings and loop for as long as the return value of strcmp()
is not 0.
The long answer is: there are more problems in this little code fragment:
The array into which you read a word is very short and you do not limit the number of characters scanf()
is likely to store there. Any user input longer than 5 non space characters will cause undefined behavior.
You do not check the return value of scanf()
. A premature end of file, such as redirecting input from an empty file, will cause an infinite loop.
Here is how the code can be written in a safer way:
#include <stdio.h>
int main(void) {
char str[80];
for (;;) {
printf("Enter the string you wanna check:");
if (scanf("%79s", str) != 1 || strcmp(str, "exit") == 0)
break;
}
return 0;
}
As suggested above, use strcmp
from the <string.h>
header file.
char str[6];
do {
printf("Enter the string you wanna check:");
scanf("%s", str);
} while(!strcmp(str, "exit"));
Try :
#include <stdio.h>
#include <string.h>
int main() {
char str[6];
do
{
printf("Enter the string you wanna check:");
scanf("%s", str);
}
while(strcmp(str, "exit") != 0);
return 0;
}