By nmagerko


2011-11-04 02:22:27 8 Comments

I am trying to get a program to let a user enter a word or character, store it, and then print it until the user types it again, exiting the program. My code looks like this:

#include <stdio.h>

int main()
{
    char input[40];
    char check[40];
    int i=0;
    printf("Hello!\nPlease enter a word or character:\n");
    gets(input);
    printf("I will now repeat this until you type it back to me.\n");

    while (check != input)
    {
        printf("%s\n", input);
        gets(check); 
    }

    printf("Good bye!");


    return 0;
}

The problem is that I keep getting the printing of the input string, even when the input by the user (check) matches the original (input). Am I comparing the two incorrectly?

8 comments

@thb 2019-02-01 21:12:20

Welcome to the concept of the pointer. Generations of beginning programmers have found the concept elusive, but if you wish to grow into a competent programmer, you must eventually master this concept — and moreover, you are already asking the right question. That's good.

Is it clear to you what an address is? See this diagram:

----------     ----------
| 0x4000 |     | 0x4004 |
|    1   |     |    7   |
----------     ----------

In the diagram, the integer 1 is stored in memory at address 0x4000. Why at an address? Because memory is large and can store many integers, just as a city is large and can house many families. Each integer is stored at a memory location, as each family resides in a house. Each memory location is identified by an address, as each house is identified by an address.

The two boxes in the diagram represent two distinct memory locations. You can think of them as if they were houses. The integer 1 resides in the memory location at address 0x4000 (think, "4000 Elm St."). The integer 7 resides in the memory location at address 0x4004 (think, "4004 Elm St.").

You thought that your program was comparing the 1 to the 7, but it wasn't. It was comparing the 0x4000 to the 0x4004. So what happens when you have this situation?

----------     ----------
| 0x4000 |     | 0x4004 |
|    1   |     |    1   |
----------     ----------

The two integers are the same but the addresses differ. Your program compares the addresses.

@chux - Reinstate Monica 2019-01-10 20:08:38

How do I properly compare strings?

char input[40];
char check[40];
strcpy(input, "Hello"); // input assigned somehow
strcpy(check, "Hello"); // check assigned somehow

// insufficient
while (check != input)

// good
while (strcmp(check, input) != 0)
// or 
while (strcmp(check, input))

Let us dig deeper to see why check != input is not sufficient.

In C, string is a standard library specification.

A string is a contiguous sequence of characters terminated by and including the first null character.
C11 §7.1.1 1

input above is not a string. input is array 40 of char.

The contents of input can become a string.

In most cases, when an array is used in an expression, it is converted to the address of its 1st element.

The below converts check and input to their respective addresses of the first element, then those addresses are compared.

check != input   // Compare addresses, not the contents of what addresses reference

To compare strings, we need to use those addresses and then look at the data they point to.
strcmp() does the job. §7.23.4.2

int strcmp(const char *s1, const char *s2);

The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

Not only can code find if the strings are of the same data, but which one is greater/less when they differ.

The below is true when the string differ.

strcmp(check, input) != 0

For insight, see Creating my own strcmp() function

@Rupani T D 2018-03-23 07:26:06

    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char s1[50],s2[50];
        printf("Enter the character of strings: ");
        gets(s1);
        printf("\nEnter different character of string to repeat: \n");
        while(strcmp(s1,s2))
        {
            printf("%s\n",s1);
            gets(s2);
        }
        return 0;
    }

This is very simple solution in which you will get your output as you want.

@chux - Reinstate Monica 2019-01-10 15:11:56

gets(); not part of standard C since C11.

@chux - Reinstate Monica 2019-01-10 15:12:53

strcmp(s1,s2) is UB as s2 contents are not specified at first.

@not2qubit 2019-07-10 12:05:32

It would be great if you could also provide the output of this snippet, in some form or another.

@mugetsu 2015-04-06 09:46:49

You can't compare arrays directly like this

array1==array2

You should compare them char-by-char; for this you can use a function and return a boolean (True:1, False:0) value. Then you can use it in the test condition of the while loop.

Try this:

#include <stdio.h>
int checker(char input[],char check[]);
int main()
{
    char input[40];
    char check[40];
    int i=0;
    printf("Hello!\nPlease enter a word or character:\n");
    scanf("%s",input);
    printf("I will now repeat this until you type it back to me.\n");
    scanf("%s",check);

    while (!checker(input,check))
    {
        printf("%s\n", input);
        scanf("%s",check);
    }

    printf("Good bye!");

    return 0;
}

int checker(char input[],char check[])
{
    int i,result=1;
    for(i=0; input[i]!='\0' || check[i]!='\0'; i++) {
        if(input[i] != check[i]) {
            result=0;
            break;
        }
    }
    return result;
}

@abarisone 2015-04-06 09:48:01

Could you please add more details about your solution?

@mugetsu 2015-04-06 10:02:21

yes this is replacement for strcmp function and solition without using string.h header @Jongware

@lukasrozs 2017-10-06 14:16:08

This does not work. When checker finds '\0' in one of the strings, it does not check the another string for '\0'. The function returns 1 ("equal") even if one string is only prefix of the other one (for example, "foo" and "foobar").

@lukasrozs 2017-10-06 14:28:51

I would use || instead of &&.

@AusCBloke 2011-11-04 02:29:51

Ok a few things: gets is unsafe and should be replaced with fgets(input, sizeof(input), stdin) so that you don't get a buffer overflow.

Next, to compare strings, you must use strcmp, where a return value of 0 indicates that the two strings match. Using the equality operators (ie. !=) compares the address of the two strings, as opposed to the individual chars inside them.

And also note that, while in this example it won't cause a problem, fgets stores the newline character, '\n' in the buffers also; gets() does not. If you compared the user input from fgets() to a string literal such as "abc" it would never match (unless the buffer was too small so that the '\n' wouldn't fit in it).

EDIT: and beaten by the super fast Mysticial once again.

@nmagerko 2011-11-04 02:30:53

I understand what you are saying, but this is just a learning example. I will not be using it for any important reason.

@AusCBloke 2011-11-04 02:32:01

@nmagerko yeah I understand. It's always important to realise that though.

@Spikatrix 2015-02-11 11:08:01

The first argument of fgets should be a char*. But stdin is a FILE*

@incompetent 2019-07-17 16:32:15

Can you please clarify the relationship/problem of "\n" and string literal? I am getting not equal result in comparing of strings (line) of a file with other whole file.

@Vishwanath Tallalli 2016-03-03 18:23:30

Whenever you are trying to compare the strings, compare them with respect to each character. For this you can use built in string function called strcmp(input1,input2); and you should use the header file called #include<string.h>

Try this code:

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h>  

int main() 
{ 
    char s[]="STACKOVERFLOW";
    char s1[200];
    printf("Enter the string to be checked\n");//enter the input string
    scanf("%s",s1);
    if(strcmp(s,s1)==0)//compare both the strings  
    {
        printf("Both the Strings match\n"); 
    } 
    else
    {
        printf("Entered String does not match\n");  
    } 
    system("pause");  
} 

@jv110 2017-08-22 20:17:02

Damn, you really need some spaces

@Ashish Ahuja 2016-02-13 07:14:40

Use strcmp.

This is in string.h library, and is very popular. strcmp return 0 if the strings are equal. See this for an better explanation of what strcmp returns.

Basically, you have to do:

while (strcmp(check,input) != 0)

or

while (!strcmp(check,input))

or

while (strcmp(check,input))

You can check this, a tutorial on strcmp.

@Mysticial 2011-11-04 02:24:16

You can't (usefully) compare strings using != or ==, you need to use strcmp:

while (strcmp(check,input) != 0)

The reason for this is because != and == will only compare the base addresses of those strings. Not the contents of the strings themselves.

@Telerik 2014-09-06 16:29:14

the same in java,which may just compare with the address.

@The Peaceful Coder 2015-06-28 15:53:00

Writing while (strcmp(check, input)) is sufficient and is considered good practice.

@chanu panwar 2016-06-25 09:55:34

@Floam 2017-11-10 18:36:03

It is safer to use strncmp! Don't want a buffer overflow!

@Deduplicator 2019-02-01 21:18:32

@Floam If you don't actually have strings, but zero-padded sequences of non-zero characters of known length, sure, that would be the right incantation. But that's something completely different!

Related Questions

Sponsored Content

60 Answered Questions

[SOLVED] How to replace all occurrences of a string?

25 Answered Questions

[SOLVED] Case insensitive 'Contains(string)'

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

85 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

42 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

65 Answered Questions

[SOLVED] What is the difference between String and string in C#?

3 Answered Questions

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

76 Answered Questions

[SOLVED] How do I iterate over the words of a string?

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2144887 View
  • 2903 Score
  • 76 Answer
  • Tags:   c++ string split

16 Answered Questions

[SOLVED] Why is char[] preferred over String for passwords?

Sponsored Content