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.

Recommended Answers

All 7 Replies

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()

Use strcmp() function.

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')) {
	if(i>0) {
		for(j=0;j<strlen(s);j++) {

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

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

char a[10];
//if u enter "hello world"
//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.


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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.