473,813 Members | 3,379 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
11 5887
Lew Pitcher <lp******@sympa tico.ca> wrote in message news:<53******* ****@merlin.l6s 4x6-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******@sympa tico.ca> wrote in message news:<53******* ****@merlin.l6s 4x6-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
12484
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
17134
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
8310
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
5279
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
3215
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
2189
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
3033
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
9734
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
9607
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10404
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...
0
9220
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7678
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5568
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
5704
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3881
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3029
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.