My prob' is that when I type 'Amanda' when the program asks for my name, it returns Hi. I want it to return Howdy when I input 'Amanda', and hello for all other strings.

This is my program:

#include <stdio.h>

int main()
{
	int		nothing;
	char	        namn[20];
	printf("What's your name?\n");
	scanf("%s", name);
	if(name == "Amanda")
		printf("Howdy");
	else
		printf("hello");
	scanf("%d", &nothing);
	return 0;

Recommended Answers

All 4 Replies

Try the function strcmp or strncmp.

I'm a total rookie at C so that doesnt make any sense to me :P

You must realize that in C strings are not first class citizens. There's no support for them in the language. There's no operator to compare them. There's strictly speaking no such thing as a string.
What is there is a memory region occupied by bytes, and a pointer to that region. You may think of it as an address of the region.

The comparison operator '==' compares just those addresses.

Now notice that in your program there are two distinct memory regions: one called "name", and another one, where lives the string literal "Amanda". They are distinctly different; they appear at the different addresses. Of course the comparison fails.

What you really want to do is to test that those regions contain the same data. For that, you need to compare them byte by byte. You may do it manually (I bet you know what the for loop is), or call a library function such as strcmp, which exists specifically for that purpose.

Thanks alot for the detailed answer. Now i get it. :)

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.