Jump to content

[ASK]Compare 2 String

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
nitediver

nitediver

    Newbie

  • Members
  • PipPip
  • 14 posts

#include <stdio.h>

main()

{

char a[10], b[10];

clrscr();

printf("name1 : ");fgets(a,10,stdin);

printf("name 2 : ");fgets(b,10,stdin);


if(a = b){

	printf("same");

}else{

	printf("different");

	}

getch();

return 0;

}


Even i input different string the output always say first statement / "same" ?

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
... please use int main() instead of just main().

Your problem is if (a = b). You used an assignment operator (=), which always returns true if you're assigning any number other than 0, and not the comparison operator (==). This still wouldn't work because the comparison operator doesn't compare strings, it compares addresses in the case of char arrays. To compare strings you have to include string.h and use strcmp(). You can look up strcmp() on Google.
Wow I changed my sig!

#3
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
A. = is an assignment. == is a comparison.
B. That isn't how you compare strings in C...use strcmp

Edit: Bawh, dammit Zeke :)

#4
nitediver

nitediver

    Newbie

  • Members
  • PipPip
  • 14 posts
@zeke
thx, im new in C,
when do we need using int main?

@tktech
thx, helpful
but i need compare from input, not based on pre-written value...

#5
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts

nitediver said:

when do we need using int main?
All of the time. 100% of every single time you make a program ever in C or C++. main is required to return a value to the operating system, and granted many compilers will implicitly declare main as int (some will even accept it if you declare it as void), it should always be done explicitly, should always be int, and you should always return 0 at the end when you're done, because some compilers won't do all of this by themselves, and on other systems this will actually cause you harm. Further, it's simply good practice. There's no real reason not to, and it's much more painless to stick to the standards.

EDIT: Granted, I cited many articles that talked about void main, there simply isn't as much information about main without a return type. Most of these articles address that as well.
Wow I changed my sig!

#6
nitediver

nitediver

    Newbie

  • Members
  • PipPip
  • 14 posts
ok thx...
i'll dig up strcmp...