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

Recommended Answers

All 3 Replies

use 'strcmp'

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;
}

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.

Be a part of the DaniWeb community

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