Hi All

Can some body tell me how to compare two strings that has spaces,

I have inputed one string using scanf() and the other using gets(), both of the strings are array of characters.

Well one problem is scanf doesn't normally catch spaces to store in strings.
The other problem is gets is a horrible function that shall never be used again.

Read two strings using fgets()

Thats the problem i have to read one string using scanf and the other using fgets(). and I need to compare them using strcmp. which returns false.

Here is how I solved this problem

fgets puts '\n' at the end of every string. so when i compare it with other string which I got using scanf, I got false result. So I trimed the the extra '\n' creating a function of my own which trimed extra spaces, tabs and new lines at the end of string. here is the code of trim function:

void trim(char *s)
{
	int i=0,j;
	while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n')) {
		i++;
	}
	if(i>0) {
		for(j=0;j<strlen(s);j++) {
			s[j]=s[j+i];
		}
	s[j]='\0';
	}

	i=strlen(s)-1;
	while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n')) {
		i--;
	}
	if(i<(strlen(s)-1)) {
		s[i+1]='\0';
	}
}

Dear waqarafridi,
if you use scanf to get a string it will never take spaces so no question of triming.
e.g

char a[10];
scanf("%s",a);
//if u enter "hello world"
printf("%s",a);
//o/p will be "hello"

Its the limitation of scanf.
and for gets ..we dont specify the size of the string we are taking so it may lead to disaster.

Thanks.
DP

I took it from a file and and the last character on that line was '\n', so due to this my comparison was returning false. so when i trimed it the result was OK

ohhh so u used fscanf().ok.fyn then.If u got your code done mark it as solved to assist the forum.
Thanks,
DP

This article has been dead for over six months. Start a new discussion instead.