In Python:
while True:
x = raw_input("enter a string:")
if "quit" in x:
print("good bye")
break
what is equivalent in c:
#include <stdio.h>
int main()
{
char sent[1000];
while(1){
printf("Enter a sentence:");
//scanf("%s",&sent);//
fgets(sent,1000,stdin);
if (strcmp(sent,"quit") == 0){
printf("Good Bye.\n");
break;
} else {
continue;
}
}
return 0;
}
if i use scanf i get the result,but no space and newlines can be entered.
using fgets it does not break if quit entered.i need help.
%s
does not accept whitespace characters.
fgets
stops at and consumes newlines. Either use strncmp
and compare only 4 characters or compare to "quit\n"
.
(Actually you should really not use strcmp
or any of the un-delimited string functions. They’re unsafe unless you’re dead certain that the string arguments will be null-terminated.)
How to compare in c. In python, I can store the user input and compare it to “quit” but in c how should I compare. Like sent == “quit\n”. It is not exiting.
Enter a sentence:hello
Enter a sentence:hiii
Enter a sentence:(ENTER)
fkc
Enter a sentence:hiii hello
Enter a sentence:Enter a sentence:
scanf works fine but it doesn’t allow space and when I press enter it waits still I enter the input. In fgets I can press enter or space but does’nt exit when pressed quit.
Sorry, I wasn’t clear. Try this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char sent[1000] = { '\0' };
while (1) {
printf("Enter a sentence: ");
fgets(sent, 1000, stdin);
if (strncmp(sent, "quit", 4) == 0) {
printf("Goodbye.\n");
return 0;
}
}
}
1 Like