There is nothing wrong syntactically in your code (i.e. it compiles cleanly), but logically it will never do what you expect it to do. The ==
and !=
operators in C are good for checking that two logical values are equivalent or not. Eg. say the user enters the value "quit" into stdin
. then the expression input != "quit"
means that !=
will be evaluate the addresses of each buffer. for illustration, it would be equivalent to the following:
unsigned int address1 = &input[0];//uaddress of input char array
unsigned int address2 = &"quit"[0];//address of string literal
while(address1 != address2) {
The two strings will never be located in the same location, and the while(){
will never exit.
The proper way to compare strings in C is by using one of the string compare functions, strstr()
or strcpy()
.
But then this brings us to the second part of the problem. A string buffer populated using scanf()
with a format specifier: "%s" will always include the last character the user typed in, i.e. the newline character: \n
. So what you believed to be "quit" is actually "quit\n". Resulting in a failed string compare. (if using strcmp()
, which in turn will cause your loop to never exit:
If input
contains "quit\n" and the string literal (2nd argument) contains quit
, the expression: (Again, the user enters "quit", it is captured into input
as "quit\n"
)
while(strcmp(input, "quit") != 0 { //will not exit
The core issue here:
Change:
while (input!= "quit") {
To:
while (strcmp(input,"quit") != 0) {
The following code addresses this and other issues below. The following example uses strcmp()
.
Modified code with comments:
#include <stdio.h>
int main() {
char input[50];//use a bigger value for array
printf("Give your input: \n");
scanf("%49s", input);//scanf picks up the newline
// | added width specifier to prevent overflow, and removed &
input[strcspn(input, "\n")] = 0;//removes newline character
while (strcmp(input,"quit") != 0) {//use string compare function"
printf("%s\n", input);
printf("Give your input: \n");//prompt user each interation
scanf("%49s", input);//remove '&'
// | added width specifier to prevent overflow, and removed &
input[strcspn(input, "\n")] = 0;//removes newline character
}
return 0;
}