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

  • Thread starter Thread starter ksepe
  • Start date Start date
  • Tags Tags
    Comparison String
Click For 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.
 
Anthropic announced that an inflection point has been reached where the LLM tools are good enough to help or hinder cybersecurity folks. In the most recent case in September 2025, state hackers used Claude in Agentic mode to break into 30+ high-profile companies, of which 17 or so were actually breached before Anthropic shut it down. They mentioned that Clause hallucinated and told the hackers it was more successful than it was...

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
Replies
7
Views
2K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
Replies
14
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
16
Views
6K