using fgets and strcmp in C [duplicate] - c

This question already has answers here:
strcmp on a line read with fgets
(6 answers)
Closed 9 years ago.
I'm trying to get a string input from the user and then run different functions depending on the input they've entered.
For example, say I asked, "What is your favorite fruit?" and I want the program to comment depending on what they enter...I'm not sure how to do this. Here's what I have so far:
#include <stdio.h>
#include <string.h>
char fruit[100];
main() {
printf("What is your favorite fruit?\n");
fgets (fruit, 100, stdin);
if (strcmp(fruit, "apple")) {
printf("Watch out for worms!\n");
}
else {
printf("You should have an apple instead.\n");
}
}
When I run the program, no matter what I enter, it never does the else statement.
Thanks for your help!

Note two things in your code:
fgets keeps the trailing '\n'. the associated char in fruit should be replaced with a '\0' before comparing with the string "apple".
strcmp return 0 when two strings are the same, so the if clause should be changed based on what you mean.(The fruit and "apple" be equivalent in the if clause)
Standard usage of C main function is int main(){ return 0;}
The revised code:
#include <stdio.h>
#include <string.h>
char fruit[100];
int main() {
printf("What is your favorite fruit?\n");
fgets (fruit, 100, stdin);
fruit[strlen(fruit)-1] = '\0';
if (strcmp(fruit, "apple") == 0) {
printf("Watch out for worms!\n");
}
else {
printf("You should have an apple instead.\n");
}
return 0;
}

Change the if condition to the following:
if(strcmp(fruit,"apple") == 0)
strcmp returns 0 strings if match. You should always compare the result using == operator

strcmp returns 0 if the inputs match, some value>0 if the left is "greater" than the right, some value<0 if the left is "lesser" than the right. So usually you want to simply test for equality with strcmp(...)==0. But there is also the clever version: !strcmp(...). Even if you don't use this style, it's useful to learn to recognize it.
And remember that fgets does not remove the newline character '\n' from the string.

Related

how to set equal two character values I tried but I cannot do it it compiled but don't support to if function [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 1 year ago.
#include<stdio.h>
void main(){
char marital[5];
printf("enter your marital details-");
scanf("%s",&marital);
if(marital=="male"){
printf("you are insured");
}
}
char gender[7];
scanf("%s",&gender);
char *message=(!strcmp(gender,"male"))?"gender is male":"gender is female";
printf("%s\n",message);
There are a couple of issues in your code:
main() should not return void. Its proper return value in an int.
You don't need to pass the address of marital to scanf() since strings in C are just pointers to arrays of char.
scanf() is a dangerous function. You should not use it to read user input. Use fgets() function, it reads an entire line and is much safer.
if(marital=="male") you are basically comparing two pointers, not the actual strings. You have to use strcmp().
That said, here's how your code should be:
#include <stdio.h>
#include <string.h> // for strcmp()
int main()
{
char marital[5];
printf("Enter your marital details: ");
fgets(marital, sizeof marital, stdin);
marital[strcspn(marital, "\n")] = `\0`; // fgets reads \n too so remove it
if(strcmp(marital, "male") == 0)
printf("you are insured");
}
You should use strcmp()to compare char arrays (strings) in C Programming Language.
Also remember to add the string ending char '\0'.
#include <unistd.h>
#include <string.h>
#define INSURED "You are insured\n"
int main () {
char marital[5];
int n = read(0, marital, 5);
marital[n - 1] = '\0';
if ( strcmp(marital, "male") == 0 ) {
write(1, INSURED, strlen(INSURED));
}
return 0;
}
strcmp() returns an integer
0 if strings are equal
> 0 if the first non-matching character in str1 is greater (in ASCII) than that of str2.
< 0 if the first non-matching character in str1 is lower (in ASCII) than that of str2.

Error in string do while [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
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;
}

Compare a variable and a string

I am trying to code a C program to start specific functions on the OS X El Capitan.
The code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char mainchoice;
printf(">>> ");
scanf("%s", &mainchoice);
if (strcmp(&mainchoice, "start ftp") == 0) {
system("ftp");
}
else if (strcmp(&mainchoice, "start say") == 0) {
system("say hello");
}
else {
system("say Error")
}
}
This is just a sample code.
When I run it, it always says error via the say command. What am I doing wrong?
Focus here:-
char mainchoice; //declared as a char
scanf("%s", &mainchoice); //using the %s placeholder which is for string
//for character it is %c
Getting the logic behind your code is you want to enter a String not a character.
Make an array of characters like this:-
char mainchoice[20]; //this can hold your string, one character at one index each of the array
Since, your are using multi word in string comparison("start say")
(strcmp(&mainchoice, "start say") == 0)
scanf does not work for multi words. scanf stops reading from the keyboard as soon as you provide a whitespace, tabs, newline.
For solving that problem, use fgets. It's the best way to read multi words or even whole sentences. Never use gets()! It is vulnerable to buffer overflow!
fgets(mainchoice, 20, stdin);
you are declaring mainchoice as a character rather then a string.
use char mainchoice[10]; to create a string.
and replace scanf("%s",&mainchoice) with fgets(mainchoice, 10, stdin);
size is 10 because you are comparing it with a string of length 9, so(9+1 null=10) 10 are enough.

fgets reading more char than it should

I'm developing a code where the user will type several paragraphs and it will stop reading when the user begin a paragraph with "END". The code will manipulate the string by counting each letter and showing a graph and blah blah blah, but this is irrelevant to the question.
The thing is: which paragraph must have no more than 1000 characters.
A smaller version of the code is the following (considering I just want to storage 5-char-string - even though I'll expand that).
#include <stdio.h>
#include <string.h>
int main()
{
char paragraph[5];
for ( ; ; )
{
fgets(paragraph, 5, stdin);
if (paragraph[0]=='E' && paragraph[1]=='N' && paragraph[2]=='D')
{ return 0; }
printf("%s", paragraph);
}
return 0;
My problem is: if I type more than 5 characters, the printf function still prints more than 5 characters, I don't know why. I've already checked everything I could possible check.
Help a beginner like me, please.
fgets() reads in at most one less than size characters from stream and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A terminating null byte ('\0') is stored after the last character in
the buffer.
So when entering more than 4 characters (newline included) only 4 is read and the rest stays in the buffer ready to be read next fgets.
Your printf will not print any newline in this case and will be called multiple times, making it look like printing more than 4 characters.
As suggested in comments, try printf("[%s]", paragraph); to see the individual printf calls.
You should use strstr in string.h because it's cleaner.
if (strstr(paragraph, "END"))
return 0;
instead of
if (paragraph[0]=='E' && paragraph[1]=='N' && paragraph[2]=='D')
return 0;
Try modifying your code in the following way and you'll immediately see what actually happens with the fgets() function when you enter more characters than the size of your buffer. It doesn't read from the keyboard, but from the stdinbuffer. These SO posts may also be interesting for you to read:(1), (2). Enjoy the demo and be sure to thoroughly read the man pages.
#include <stdio.h>
int main()
{
char paragraph[5];
for ( ; ; )
{
printf("Enter the string: \n\t");
if(fgets(paragraph, 5, stdin) != NULL)
printf("%s\n", paragraph);
if (paragraph[0]=='E' && paragraph[1]=='N' && paragraph[2]=='D')
return 0;
}
return 0;
}

Why "while" loop does not end when condition is met? [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 7 years ago.
I have an apparently easy issue but I just cannot get what am I doing wrong.
I've got a code which will test a 60 character entered text in console and if in that text the "terrorist" word appears it will prompt the message "suspect text" and when that word does not appear it would show "nothing suspect".
The text entering "mode" should finish when the word "done" is entered. This seems to be my problem because my while loop just does not want to end.
Any hints?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
int start_with (char *sir1, char *sir2)
{
int i,j,k;
int len_sir2=strlen(sir2);
char sir3[60]="";
for (i=0;i<=len_sir2;i++)
{
sir3[i]=sir1[i];
}
k=(strcmp(sir2,sir3)) ? 0:1;
return k;
}
int main()
{
char *txt1;
char sir1[60]="", sir2[60]="terorist", sir_test[60]="done";
int i,j,lensir1, contor=0,buf_de_la=0, buf_la;
while (sir1!=sir_test)
{
printf("Enter desired text and press ENTER \n");
gets(sir1);
printf("\n");
buf_la=strlen(sir1);
char *txt1="Nothing suspect";
while (buf_de_la<buf_la-7)
{
char sirbuf[60]="";
j=buf_de_la;
for (i=0;i<=7;i++)
{
sirbuf[i]=sir1[j];
j=j+1;
}
if (start_with(sirbuf,sir2)==1)
{
txt1="SUSPECT text entered!";
break;
}
buf_de_la=buf_de_la+1;
}
printf("%s\n",txt1);
getch();
system("cls");
}
return 0;
}
You should compare C-style strings by using strcmp, like this
while (strcmp(sir1, sir_test) != 0)
This happens because when you do sir1!=sir_test, what you are actually testing is if both character arrays are pointing to the same address in memory, which is not true, since they are two different character arrays located at two different memory addresses.
Instead, what you want to do is compare the characters contained in each variables memory space, and that's what strcmp does: it compares character by character until a null terminating character is found.
Instead of while (sir1!=sir_test), try this: while (strcmp(sir1,sir_test)). strcmp, strcmpi etc. are the proper functions to be used for string comparisons. They are declared under the string.h header file.
The issue is with your comparison while (sir1!=sir_test) which is wrong. It actually compares the addresses of the two strings. You can use strcmp or various other forms of the same function for comparing strings.
A small change which could make your code working is shown below..
do{
printf("Enter desired text and press ENTER \n");
.
.
.
system("cls");
}
while (strcmp(sir1,sir_test));

Resources