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

Dani AI

Generated

The core issue is that buff == "Asto.cfg" compares two pointers (addresses), not the characters they point to. That is why the test usually fails even when the printed string looks identical. was pointing to this same pointer-vs-content distinction. Also check the literal spelling in the code — a missing or extra character (for example Asto.cfg vs Astro.cfg) will of course cause a content mismatch.

Two straightforward fixes: use the C function that compares C-strings, or use C++ strings. As suggested, strcmp compares contents; as suggested, std::string compares contents with operator==. Example (safe diagnostics + content compare):

#include <iostream>
#include <cstring>

int main()
{
    const char arr[] = "Astro.cfg";
    const char* buff = arr;

    std::cout << "String: " << buff << '\n';

    if (std::strcmp(buff, "Astro.cfg") == 0)
        std::cout << "Success\n";
    else
        std::cout << "Fail\n";

    std::cout << "addr buff:    " << static_cast<const void*>(buff) << '\n';
    std::cout << "addr literal: " << static_cast<const void*>("Astro.cfg") << '\n';
    return 0;
}

Troubleshooting notes: print the pointer addresses to confirm you are not accidentally comparing addresses. Use strncmp when you only want to compare a fixed number of bytes. For case-insensitive checks use platform-appropriate functions (strcasecmp or _stricmp). Prefer std::string in C++ code to avoid manual NUL-termination, buffer overruns and pointer confusion (see strcmp documentation and std::string comparisons).

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.