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.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

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