473,396 Members | 1,997 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

strcmp() And if

Shouldn't this code work? If not, why shouldn't it?

#include <stdio.h>

int main(void)

{

char yesno[10];
char *yes = "yes";
char *no = "no";

printf("Select: yes or no\n");
fgets(yesno, sizeof(yesno), stdin);

if(strcmp(yes, yesno) == 0)
{
printf("yes\n");
}
if(strcmp(no, yesno) == 0)
{
printf("no\n");
}

return 0;

}
Nov 14 '05 #1
11 5840
ei*****@grex.cyberspace.org (Eirik) writes:
Shouldn't this code work? If not, why shouldn't it?
That depends on how you define "work". If the program receives the
characters 'y', 'e', and 's', immediately followed by an end-of-file
condition, on standard input, it prints "yes" followed by a newline
character. If it receives 'n' and 'o', again followed by an end-of-file
condition, it prints "no" followed by a newline character. If that is
what the program is supposed to do, then it works.

If `fgets' reads a full line, then the program cannot print either "yes\n"
or "no\n", because `fgets' stores the final newline character if there is
one.
#include <stdio.h>
Since the program uses `strcmp', I recommend that you also include
<string.h>.
int main(void)

{

char yesno[10];
char *yes = "yes";
Since the pointer itself is not modified, and the memory pointed to
(a string literal) cannot be modified, I recommend that you make both
constant:

const char *const yes = "yes";
char *no = "no";
Likewise.
printf("Select: yes or no\n");
The simpler `puts' function would also have been possible here.
fgets(yesno, sizeof(yesno), stdin);
As explained above, `fgets' stores the final newline character if there is
one before end-of-file or an error occur. Also, you might want to check
the return value: it is a null pointer if an error occurs or end-of-file
occurs before at least one character has been read.
if(strcmp(yes, yesno) == 0)
{
printf("yes\n");
Again, `puts' would also have been possible.
}
if(strcmp(no, yesno) == 0)
Since this condition cannot be true if the previous condition has already
been true, you could avoid an unnecesary test by writing

else if (strcmp (no, yesno) == 0)
{
printf("no\n");
Again, `puts' would also have been possible.
}

return 0;

}

Martin
Nov 14 '05 #2
fgets include the first CR caracter that the user type to validate
his answer that's why strcmp returns 1 and not 0.

To avoid that you can do :

if(strncmp(yes, yesno, 3) == 0)
{
printf("yes\n");
}

--
Un Véritable lui, code en fortran.

"Eirik" <ei*****@grex.cyberspace.org> a écrit dans le message de news:
76*************************@posting.google.com...
Shouldn't this code work? If not, why shouldn't it?

#include <stdio.h>

int main(void)

{

char yesno[10];
char *yes = "yes";
char *no = "no";

printf("Select: yes or no\n");
fgets(yesno, sizeof(yesno), stdin);

if(strcmp(yes, yesno) == 0)
{
printf("yes\n");
}
if(strcmp(no, yesno) == 0)
{
printf("no\n");
}

return 0;

}

Nov 14 '05 #3
ei*****@grex.cyberspace.org (Eirik) writes:
Shouldn't this code work? If not, why shouldn't it?

#include <stdio.h>

int main(void)
{
char yesno[10];
char *yes = "yes";
char *no = "no";

printf("Select: yes or no\n");
fgets(yesno, sizeof(yesno), stdin);
If you enter "yes" then yesno will contain "yes\n",
if(strcmp(yes, yesno) == 0)
{
printf("yes\n");


so you won't get here.
Nov 14 '05 #4

because you enter no followed by a carridge return.

try defining these and re-running the code :o)

char yesno[10];
char *yes = "yes\n";
char *no = "no\n";

JohnO

On 13 Dec 2003 06:39:34 -0800, ei*****@grex.cyberspace.org (Eirik)
wrote:


Shouldn't this code work? If not, why shouldn't it?

#include <stdio.h>

int main(void)

{

char yesno[10];
char *yes = "yes";
char *no = "no";

printf("Select: yes or no\n");
fgets(yesno, sizeof(yesno), stdin);

if(strcmp(yes, yesno) == 0)
{
printf("yes\n");
}
if(strcmp(no, yesno) == 0)
{
printf("no\n");
}

return 0;

}


Nov 14 '05 #5
Eirik <ei*****@grex.cyberspace.org> wrote:
Shouldn't this code work? If not, why shouldn't it? #include <stdio.h> int main(void) { char yesno[10];
char *yes = "yes";
char *no = "no"; printf("Select: yes or no\n");
fgets(yesno, sizeof(yesno), stdin); if(strcmp(yes, yesno) == 0)
{
printf("yes\n");
}
if(strcmp(no, yesno) == 0)
{
printf("no\n");
} return 0; }


Depends on what you mean with "work". It will work in the sense that
the program is going to run, but not in the sense that it will print
out "yes" when you enter "yes" or "no" when you enter "no".

The problem is that fgets() also stores the final '\n' character in
your 'yesno' buffer, which you get from pressing the <ENTER> key.
So you either have to strip it off from the 'yesno' buffer or you
have to compare against "yes\n" and "no\n" to get the expected
result.
Regards, Jens

--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.physik.fu-berlin.de/~toerring
Nov 14 '05 #6
Eirik wrote:

Shouldn't this code work? If not, why shouldn't it?

#include <stdio.h>

int main(void)

{

char yesno[10];
char *yes = "yes";
char *no = "no";

printf("Select: yes or no\n");
fgets(yesno, sizeof(yesno), stdin);

if(strcmp(yes, yesno) == 0)
{
printf("yes\n");
}
if(strcmp(no, yesno) == 0)
{
printf("no\n");
}

return 0;

}


You forgot string.h and that fgets() returns the '\n'.

#include <stdio.h>
#include <string.h>

int main(void)
{
char yesno[10];
char *yes = "yes\n";
char *no = "no\n";
printf("Select: yes or no\n");
fgets(yesno, sizeof yesno, stdin);

if (strcmp(yes, yesno) == 0) {
printf("yes\n");
}
if (strcmp(no, yesno) == 0) {
printf("no\n");
}
return 0;
}

--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #7
Joe Wright wrote:
Eirik wrote:

Shouldn't this code work? If not, why shouldn't it?

#include <stdio.h>
int main(void)
{
char yesno[10];
char *yes = "yes";
char *no = "no";

printf("Select: yes or no\n");
fgets(yesno, sizeof(yesno), stdin);

if(strcmp(yes, yesno) == 0)
{
printf("yes\n");
}
if(strcmp(no, yesno) == 0)
{
printf("no\n");
}
return 0;
}
You forgot string.h and that fgets() returns the '\n'.

#include <stdio.h>
#include <string.h>

int main(void)
{
char yesno[10];
char *yes = "yes\n";
char *no = "no\n";
printf("Select: yes or no\n");
fgets(yesno, sizeof yesno, stdin);

if (strcmp(yes, yesno) == 0) {
printf("yes\n");
}
if (strcmp(no, yesno) == 0) {

else if (strcmp(no, yesno) == 0) { /* replace above ***/ printf("no\n");
} else printf("Don't understand \"%s\"\n", yesno); /* ADD **/ return 0;
}


See recommended mods above.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #8
Eirik wrote:
Shouldn't this code work? If not, why shouldn't it?

#include <stdio.h>

int main(void)

{

char yesno[10];
char *yes = "yes";
Here, your yes variable is a pointer to a four character array, such that
*(yes+0) == 'y'
*(yes+1) == 'e'
*(yes+2) == 's' and
*(yes+3) == '\0'
char *no = "no";
Similarly, your no variable is a pointer to a three character array, such that
*(no+0) == 'n'
*(no+1) == 'o' and
*(no+2) == '\0'

printf("Select: yes or no\n");
fgets(yesno, sizeof(yesno), stdin);
fgets() stops reading after an EOF or a newline. If a newline is read, it is
stored in the buffer. A \0 is stored after the last character in the buffer.

If your hosted environment is consistant with most environments, fgets() will
have captured a buffer that
a) has a newline character following the input data, and
b) has a \0 after the newline character.

Assuming the user entered "no", then yesno will be string of four characters
yesno[0] will be 'n'
yesno[1] will be 'o'
yesno[2] will be '\n' and
yesno[3] will be '\0'

if(strcmp(yes, yesno) == 0)
strcmp() performs a character by character comparison. Even if the user entered
"yes", if the entry was terminated by a newline, then yesno will carry "yes\n",
but yes will point to a string "yes". These are not equal (yesno carries a '\n'
where yes carries a '\0'), and the test fails.
{
printf("yes\n");
}
if(strcmp(no, yesno) == 0)
Similarly, if the user entered "no", and the entry was terminated by a newline,
then yesno will carry "no\n", but no will point to the string "no". Again, the
comparison fails because '\n' is not equal to '\0'.
{
printf("no\n");
}

return 0;

}
One way to fix this would be to change
char *yes = "yes";
char *no = "no";


to

char *yes = "yes\n";
char *no = "no\n";
--
Lew Pitcher

Master Codewright and JOAT-in-training
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.

Nov 14 '05 #10
Lew Pitcher <lp******@sympatico.ca> wrote in message news:<53***********@merlin.l6s4x6-4.ca>...
Eirik wrote:
Shouldn't this code work? If not, why shouldn't it?

#include <stdio.h>

int main(void)

{

char yesno[10];
char *yes = "yes";
Here, your yes variable is a pointer to a four character array, such that

Nitpick :: The yes variable is a pointer to a character .. specifically to
the first character in the string "yes". No type information is stored in
it. The declaration for a pointer to a four character array would be :
char (* p4array)[4];
*(yes+0) == 'y'
*(yes+1) == 'e'
*(yes+2) == 's' and
*(yes+3) == '\0'
char *no = "no";
Similarly, your no variable is a pointer to a three character array, such that

Likewise.
*(no+0) == 'n'
*(no+1) == 'o' and
*(no+2) == '\0'

printf("Select: yes or no\n");
fgets(yesno, sizeof(yesno), stdin);


fgets() stops reading after an EOF or a newline. If a newline is read, it is
stored in the buffer. A \0 is stored after the last character in the buffer.

If your hosted environment is consistant with most environments, fgets() will
have captured a buffer that
a) has a newline character following the input data, and
b) has a \0 after the newline character.

Assuming the user entered "no", then yesno will be string of four characters
yesno[0] will be 'n'
yesno[1] will be 'o'
yesno[2] will be '\n' and
yesno[3] will be '\0'

if(strcmp(yes, yesno) == 0)


strcmp() performs a character by character comparison. Even if the user entered
"yes", if the entry was terminated by a newline, then yesno will carry "yes\n",
but yes will point to a string "yes". These are not equal (yesno carries a '\n'
where yes carries a '\0'), and the test fails.
{
printf("yes\n");
}
if(strcmp(no, yesno) == 0)


Similarly, if the user entered "no", and the entry was terminated by a newline,
then yesno will carry "no\n", but no will point to the string "no". Again, the
comparison fails because '\n' is not equal to '\0'.
{
printf("no\n");
}

return 0;

}


One way to fix this would be to change
> char *yes = "yes";
> char *no = "no";


to

char *yes = "yes\n";
char *no = "no\n";

Nov 14 '05 #11
Anupam wrote:
Lew Pitcher <lp******@sympatico.ca> wrote in message news:<53***********@merlin.l6s4x6-4.ca>...
Eirik wrote:
Shouldn't this code work? If not, why shouldn't it?

#include <stdio.h>

int main(void)

{

char yesno[10];
char *yes = "yes";


Here, your yes variable is a pointer to a four character array, such that


Nitpick :: The yes variable is a pointer to a character .. specifically to
the first character in the string "yes". No type information is stored in
it. The declaration for a pointer to a four character array would be :
char (* p4array)[4];


Yes, of course. :-)
My only excuse is that I tried to simplify the explanation somewhat.
[snip]

--
Lew Pitcher

Master Codewright and JOAT-in-training
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.

Nov 14 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: muser | last post by:
The following error appears: 'strcmp' : cannot convert parameter 1 from 'char' to 'const char *'. I've already tried using single quotations. the header file only contains the struct contents....
3
by: jl_post | last post by:
Hi, I recently wrote two benchmark programs that compared if two strings were equal: one was a C program that used C char arrays with strcmp(), and the other was a C++ program that used...
53
by: Allan Bruce | last post by:
Hi there, I am reading a file into a char array, and I want to find if a string exists in a given line. I cant use strcmp since the line ends with '\n' and not '\0'. Is there a similar function...
9
by: Steven | last post by:
Hello, I have a question about strcmp(). I have four words, who need to be compared if it were two strings. I tried adding the comparison values like '(strcmp(w1, w2) + strcmp(w3, w4))', where...
13
by: Sameer | last post by:
Hi friends, I am beginner in C++. I am using g++ compiler. below is my code which gives error as " invlid conversion from 'char' to 'const char*' ..Plz help me with this. #include <iostream.h>...
36
by: Chuck Faranda | last post by:
I'm trying to debug my first C program (firmware for PIC MCU). The problem is getting serial data back from my device. My get commands have to be sent twice for the PIC to respond properly with...
0
by: noobcprogrammer | last post by:
#include "IndexADT.h" int IndexInit(IndexADT* word) { word->head = NULL; word->wordCount = 0; return 1; } int IndexCreate(IndexADT* wordList,char* argv)
47
by: fishpond | last post by:
One way I've seen strcmp(char *s1, char *s2) implemented is: return immediately if s1==s2 (equality of pointers); otherwise do the usual thing of searching through the memory at s1 and s2. Of...
2
by: thungmail | last post by:
There is partial code in C typedef struct message { int messageId; char *messageText; struct message *next; }message; ..... ..... ..... /* Get a node before a node */
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.