Searching string for characters

P

ptq2238

Hi, I've been experimenting some more with strings, I've written some
code where I want to test to see if a certain character char_a is in
the testlist string. Simple enough.
The problem is when testlist contains characters other than letters
and numbers such as comma, full stop and double quotes.

#include <stdio.h>
#include <string.h>

int main ()
{
char *testlist = "This is a test,."";
char char_a = 'a';

if (strchr(testlist,char_a) != NULL)
printf("Found in testlist \n");
else
printf("Not found in testlist \n");

return 0;
}

Upon compiling with gcc -Wall -Werror -W -O, I get
searchstring.c: In function `main':
searchstring.c:6: error: missing terminating " character
searchstring.c:7: error: parse error before "char"
searchstring.c:9: error: `char_a' undeclared (first use in this
function)
searchstring.c:9: error: (Each undeclared identifier is reported only
once
searchstring.c:9: error: for each function it appears in.)

The comma, full stop are no problems but it's the extra " that's
causing the issue.
The reason that I have a double quote in my testlist is that I want to
call another function if it's found.
Is it possible to get the extra double quote in my testlist or have I
gone about this the wrong way ?
Thank you for any advice.

Pat
 
C

Chris Dollin

The comma, full stop are no problems but it's the extra " that's
causing the issue.
The reason that I have a double quote in my testlist is that I want to
call another function if it's found.

To put a " in a string literal, you must escape it with a preceeding \.

Your C book should tell you that. If it doesn't, I'd call it broken.

--
"Our future looks secure, but it's all out of our hands." /Man and Machine/
- Magenta

Hewlett-Packard Limited registered no:
registered office: Cain Road, Bracknell, Berks RG12 1HN 690597 England
 
R

Richard Heathfield

(e-mail address removed) said:
Hi, I've been experimenting some more with strings, I've written some
code where I want to test to see if a certain character char_a is in
the testlist string. Simple enough.
The problem is when testlist contains characters other than letters
and numbers such as comma, full stop and double quotes.

#include <stdio.h>
#include <string.h>

int main ()
{
char *testlist = "This is a test,."";

Make that:

char *testlist = "This is a test,.\"";

Better still:

const char *testlist = "This is a test,.\"";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top