nbk nbk - 3 months ago 11
C Question

Grabbing The First Character of a String

I am taking in a string from the stdinput via readline() a la:

char * cmdLine = readline();


Then I want to see if the first character of the string produced via readline() is an exclamation point. But the code

if(cmdLine[0]=="!")


doesn't do that for me like I would have thought. I thought that if the string snagged from stdin was "!1" for instance then it would be true that

cmdLine[0]=="!"


If cmdLine is a pointer to a string then can't I look at each character in the string with array brackets? I know this is a stupid basic c / pointer question but this is really tripping me up...

Answer

Change "!" to '!'. You are comparing a single char to another single char.

In C you specify a char with single quotes