473,800 Members | 2,495 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5884
ei*****@grex.cy berspace.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.c yberspace.org> a écrit dans le message de news:
76************* ************@po sting.google.co m...
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.cy berspace.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.cy berspace.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.c yberspace.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***********@p hysik.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********@yah oo.com) (cb********@wor ldnet.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

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

Similar topics

6
12481
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. The whole program is part of an example found in my course work. Does strcmp only compare two sets of strings or can it be used to determine the end of the string as well? #include<iostream>
3
17132
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 std::strings with operator==(). In both programs, the first string consisted of one million characters (all the letter 'a'). The second string was always one character longer than the first string (with the letter 'a' for all the
53
8308
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 that will do this, or will I have to write my own? Thanks Allan
9
5277
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 w1 and w2 make up the first string and, w3 and w4 make up the second string. I do not want to allocate memory, then put the words together to create a string only to facilitate strcmp() comparison. My question; Does anyone know how to get the...
13
2272
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> #include <string.h> int low_range(char symbol) ; int main(int argc, char **argv)
36
3211
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 the needed data. Any ideas? Here's the code in question, see any reason why a command would not trigger the 'kbhit' the first time a serial command is sent?: Thanks! Chuck **************************************************** while(1) //...
0
2185
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
3031
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 course the reason for doing this is to save time in case equal pointers are passed to strcmp. But it seems to me that this could create an inconsistency in the degenerate case when s1 points to memory that is not null-terminated, i.e. by some freak...
2
2093
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
9690
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10505
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10275
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10253
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10033
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5471
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.