-2

I have written this code where i want to input a text, say "helloWorld" and then compare it such that if it matches the entered text then it should print the text 101 times. But, it is not working as it does not seem to compare the string in the if (string == "helloWorld") and it directly skips to the else part. Please provide necessary details on how to do it.

Here is my code:

#include<stdio.h>
#include<conio.h>

void main()

{
    int i;
    char string[30];
    clrscr();
    printf("Enter the string 'helloWorld' if you wanna see magic\n");
    scanf ("%s", string);
    printf("Your enterred Input is %s\n", string);
    if (string == "helloWorld")
    {
        for (i=0;i<=100;i++)
        {
            printf("%s\n",string);
        }
    }
    else
    {
        printf("Invalid Input\n");
    }
    getch();
}

Also, I know that in C if we enter a string using char variable[sting_length] in C, we have to enter the string without any spaces. But, is there any way to enter the string like "Hello World" and still have the whole thing printed/compared altogether?

Jack
  • 131,802
  • 30
  • 241
  • 343
Animikh Aich
  • 598
  • 1
  • 6
  • 15
  • 4
    You can't compare C strings with the `==` operator. That will compare their addresses, not their contents. Look up the standard `strcmp` function. – Nate Eldredge May 28 '16 at 01:50
  • "we have to enter the string without any spaces" - Huh? If "We" means the people from your class, this might be a restriction by your teacher. But for the rest this is nonsense and no way mandated by the C standard. – too honest for this site May 28 '16 at 03:16

1 Answers1

-2

In order to read the string with a space, you could create a loop that reads characters until it reaches a new line.

int i = 0;
char inputChar = ' ';
char* string = new char[STRING_SIZE];
do
{
     getch(inputChar);
     string[i] = inputChar;
     i++;
} while (inputChar != '\n' && i < STRING_SIZE);

In this code, STRING_SIZE is whatever size of array you choose.

In order to compare the strings, you have to check each element in order to verify that they are the same.

char compare[] = "Hello, world!";
int i = 0;
bool areEqual = true;
while (areEqual && compare[i] != '\n')
{
     if(compare[i] != string[i])
     {
         areEqual = false;
     }
}

Using these two sections of code, you should be able to read a string with spaces then compare it to any string of your choosing. The strings may also have different lengths.