C String Comparison: Debugging Error - "Hello" Output

  • Context: MHB 
  • Thread starter Thread starter ksepe
  • Start date Start date
  • Tags Tags
    Comparison String
Click For Summary
SUMMARY

The discussion centers on a coding error in C related to string comparison. The original code incorrectly uses strcpy instead of strcmp to compare the user input with the string "Quit". The corrected code utilizes strcmp(userString, "Quit") == 0 to properly check for equality, ensuring that "Goodbye" is printed when "Quit" is entered, rather than "Hello". This highlights the importance of using the correct functions for string operations in C programming.

PREREQUISITES
  • Understanding of C programming syntax
  • Familiarity with string manipulation functions in C
  • Knowledge of ANSI C standards
  • Basic debugging skills in C
NEXT STEPS
  • Learn about C string manipulation functions, focusing on strcmp and strcpy
  • Explore error handling techniques in C programming
  • Study ANSI C compliance and its implications for string handling
  • Practice debugging C code with common string-related errors
USEFUL FOR

C programmers, software developers, and students learning C who are interested in mastering string comparison and debugging techniques.

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.
 

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
4K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
16
Views
6K