-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.

Community
  • 1
  • 1
con
  • 5,767
  • 8
  • 33
  • 62

1 Answers1

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;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • thank you MikeCAT, I learned something new about C today I had never heard this before, an excellent explanation is here: http://stackoverflow.com/questions/3683602/single-quotes-vs-double-quotes-in-c – con Jun 07 '16 at 14:37
  • Is it valid to write *"." ?? – machine_1 Jun 07 '16 at 16:10