-2

I've been trying get part of a string from a char array, and for the life of me, I cannot get any of the examples I've found on StackOverflow to work: Compare string literal vs char array I've looked all over the internet for a solution, I've tried mixing pointers, strcmp, strncmp, everything I can think of.

I cannot see how to get this to work:

#include <stdio.h>

int main(void) {
 const char S[] = "0.9";
 if (S[1] == ".") {
    puts("got it");
 }
 return 0;
}

I realize posting this may ruin my reputation... but I could not find the solution.... similar articles didn't work.

thanks in advance for your help :/

EDIT: I was not aware of the correct search terms to use; that's why I didn't find the specified original.

1
  • 3
    You are comparing a char value to a char pointer. Change "." to '.'. Commented Jun 7, 2016 at 14:31

1 Answer 1

4

"." is a string literal. What you want should be a character constant '.'.

Try this:

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

int main(void) {
 const char S[] = "0.9";
 if (S[1] == '.') {
    puts("got it");
 }
 return 0;
}

Alternative (but looks worse) way: access an element of the string literal

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

int main(void) {
 const char S[] = "0.9";
 if (S[1] == "."[0]) {
    puts("got it");
 }
 return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you MikeCAT, I learned something new about C today I had never heard this before, an excellent explanation is here: stackoverflow.com/questions/3683602/…
Is it valid to write *"." ??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.