How do I use strings in OS X?

jjones!

Registered
I'm trying to write a simple little program using strings (which used to work fine) in project builder, but I can no longer get strings to work. Here's an example of code that used to compile for me, but now doesn't:
NOTE: assume there are "<" and ">" around each header file. (I couldn't get the names of the header files to show up with them in the actual code.)
Code:
#include iostream.h
#include cstdlib
#include stdio.h
#include string
#include fstream.h

int main()
{
    [B] string filename;[/B] 
    cerr << "document: ";
     [B]cin >> filename;[/B]
     cout << "the document was: " << filename << endl;
}

With g++ on some linux boxes at school, this compiles. With gcc, it doesn't.
With project builder (at home), this doesn't compile because it uses gcc. How do I achieve the functionality of the above program with project builder (and preferably using string.h)?


here are the errors from trying to compile this with project builder (gcc):

main.cpp: In function `int main()':
main.cpp:9: `string' undeclared (first use this function)
main.cpp:9: (Each undeclared identifier is reported only once for each function it appears in.)
main.cpp:9: parse error before `;' token
main.cpp:11: `filename' undeclared (first use this function)

click here to e-mail me
also, I'm running 10.2.3

-Thanks
 
why is your main() int? It doesn't return an int...

And should there be a .h after string?
I havn't really used strings too much so I can't really help you with much more.
 
string exists in the std namespace.

You want to have either "using namespace std" after you include the string's header file, OR, you can do "using std::string" OR, everywhere you want to use a string object you can use std::string

Since you're using other objects such as cout which are in the std namespace as well, it'll be easiest to just use "using namespace std" after all your includes.

You do also want to return something at the end of your program, such as "return 0;"

The "string" header file is the ANSI standard header, while the "string.h" header file can be written to be platform specific. It's best to always use only string and not string.h to conform to ANSI standards.
 
You're mixing a little bit C and C++.
You're including stdio.h which is the "standard"-C header, but your using cin and cout, which are C++-commands.

I've hopefully two solutions.

1) Try to include only iostream (take the .h away).

2) use printf and scanf (C-commands).
 
"using namespace std;" did the trick, thanks. Is there some reason why I've never needed that before? (because I haven't).

-jay
 
Because you updated you Dev Tools to the newer GCC which is more standards compliant. Gotta love those moving standards ;)

-Eric
 
Back
Top