0

The following is giving output as follows
String:Astro.cfg
Fail

If buff is Astro.cfg, it has to give success output, but it is giving fail. I want to print Success.. Please guide me regarding this pointer usage..

#include<iostream>
using namespace std;

int main()
{
	char arr[]="Asto.cfg";
	char *buff=&arr[0];
	printf("String:%s",buff);

	if(buff=="Asto.cfg")
	{
		cout<<"Success";

	}
	else 
		cout<<"Fail!!!!";
	cin.get();
}
4
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by CoolGamer48
0

What Agni said.
But if you want to make your life a whole lot easier, use std::strings:

#include<iostream>
#include <string>
using namespace std;

int main()
{
    string buff = "Asto.cfg";
    cout << buff << "\n";

    if(buff=="Asto.cfg")
        cout<<"Success";
    else 
        cout<<"Fail!!!!";
    cin.get();
    return 0;
}
0

Yes - std::strings are good. char* and char arrays are bad.

In case you're wondering why you can't use the == operator with char*, think about it. buff is a pointer to a char. In other words, it contains the address of a single char, and so should be compared to other addresses of chars. The line if(buff=="Asto.cfg") is seeing if "Asto.cfg" is the address of the char 'A' that begins your string. It isn't.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.