1

I was curious if I could write C programs in the Mac Terminal. It seems yes, but when I start trying to use Strings, I get errors when compiling.

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

int main(void) {
        string s = "chris";
        printf("hello %s \n", s);
}

When I compile this I get a message saying use of undeclared identifier 'string' - string s = "chris";

I have trying adding using namespace std; but is says that using is undefined. I have tried both #include <string> and #include <string.h>

Any thoughts would be appreciated.

2
  • 4
    There is no "string" in C; it sounds like you're mixing C and C++ concepts. Jan 27, 2014 at 22:47
  • 1
    And in C++ you have #include <string> to use std::string. But most importantly, don't try to write C or C++ trying random stuff, get yourself a book first. Jan 27, 2014 at 22:48

1 Answer 1

2

string is a standard C++ library class. Use const char * instead:

#include <stdio.h>

int main(int argc, const char **argv) {
        const char *s = "chris";
        printf("hello %s \n", s);
        return 0;
}
3
  • Hmm, ok. I am following along with an online course and they are saying they are using "C" and they are using strings, maybe my lines got crossed somewhere.
    – Chris
    Jan 27, 2014 at 22:58
  • 1
    @Chris Well unless you do typedef const char *string; before main(), then I think you have your wires crossed. If they are using C++ then that %s in the printf() will break and you generally use std::cout instead with C++.
    – trojanfoe
    Jan 27, 2014 at 22:59
  • Even if you did typedef it, string is a reserved identifier in C, so it would still be wrong.
    – Crowman
    Jan 27, 2014 at 23:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.