MHB C String Comparison: Debugging Error - "Hello" Output

  • Thread starter Thread starter ksepe
  • Start date Start date
  • Tags Tags
    Comparison String
AI Thread Summary
The discussion centers on a coding error in a C program where the output is incorrectly producing "Hello" instead of "Goodbye" when the input "Quit" is entered. The issue arises from the use of the `strcpy` function in the conditional statement, which does not compare strings but rather copies them. Instead, the correct function to use for comparing strings is `strcmp`, which returns 0 when the two strings are identical. The corrected code snippet provided uses `strcmp` to properly check if `userString` matches "Quit", ensuring that "Goodbye" is printed when the input is correct. Additionally, it is noted that `strcpy` returns a pointer to the destination string, which is not suitable for comparison purposes.
ksepe
Messages
5
Reaction score
0
I am trying to compare a computer generated word to display the following however, when Quit is entered it produces the output "Hello". What is my error in the code?

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

int main(void) {
   char userString[50];

   strcpy(userString, "Quit");

   /* Your solution goes here  */
if (strcpy(userString,"Quit")==0){
   printf("Goodbye\n");
}
else {
   printf("Hello\n");
}
   return 0;
}
 
Last edited by a moderator:
Technology news on Phys.org
On an ANSI-compliant system, strcmp(const char *str1, const char *str2) returns 0 if the strings str1 and str2 are identical.

Try

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

int main(void) {
		char userString[50];

		strcpy(userString, "Quit");

		/* Your solution goes here */

		if (strcmp(userString, "Quit") == 0){
			printf("Goodbye\n");
		}
		else {
			printf("Hello\n");
		}

		return 0;
}

The function strcpy(char *destination, char *source) returns a pointer to the destination string: a non-zero value.

*Note: you may post formatted source code by enclosing the source code in [code]...[/code] tags.
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
Back
Top