Reputation: 2504
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char word[100];
while (word != "hello") {
system("clear");
printf("\nSay hello to me : ");
scanf(" %s", word);
}
printf("congrats, you made it !");
return 0;
}
In this code : if i enter anything but hello, the loop continue. However, entering the ENTER key will not loop again, it will just add a line.
I read somewhere that using getchar() might help but I'm kinda new to the C developpement and I'm stuck here searching for hours how to make it works.
EDIT 0 :
Removed
while (word != "hello")
char word[100];
scanf(" %s", word);
Added
#include <string.h>
while (strcmp(word, "hello") != 0)
char word[100] = {0};
fgets(word, 6, stdin);
EDIT 1 :
I tried to include in my code something like that
fgets(word, 6, NULL);
But it got me a segmentation fault.
**EDIT 2 : **
The correct working input is :
fgets(word, 6, stdin);
So it worked, but adding more than 6 character to the question like :
Say hello to me : hello from the inside
Will just print :
Say hello to me :
Say hello to me :
So I just modified the function like that :
fgets(word, 100, stdin);
But now it will not get me any input to work
Upvotes: 1
Views: 394
Reputation: 153488
@dbush well answered OP initial concerns.
OP is now using fgets(word, 100, stdin);
and types in h e l l o Enter. word[]
is then filled with "hello\n"
and this does not pass strcmp(word, "hello") != 0
.
Solution: strip final '\n'
.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 100
int main() {
char word[BUFFER_SIZE] = { 0 };
while (strcmp(word, "hello") != 0) {
system("clear");
printf("\nSay hello to me : ");
// insure buffered output is flushed
fflush(stdout);
// Avoid magic numbers, use `sizeof word`
// Test if input was received
if (fgets(word, sizeof word, stdin) == NULL) {
fprintf(stderr, "\nInput closed\n");
return 1;
}
// lop off potential trailing \n
word[strcspn(word, "\n")] = '\0';
}
printf("congrats, you made it !\n");
return 0;
}
Upvotes: 0
Reputation: 223917
Three things:
You don't need the space in the scanf
format string. The %s
format specifier already ignores leading whitespace. So instead of " %s"
use "%s"
.
The main problem is word != "hello"
. That's not how strings are compared. What you're actually doing is comparing the address of word
with the address of the string constant "hello"
. To do a string comparison, use strcmp
. If it returns 0, the strings are the same, so your while
loop should check for non-zero:
while (strcmp(word,"hello")) {
Be sure to #include <string.h>
to get the declaration of strcmp
.
Finally, you need to initialize word
so that the initial string comparison doesn't invoke undefined behavior by reading uninitialized data:
char word[100] = {0};
Upvotes: 3