cant declare a string variable...

i'm sorry if this sounds very n00bish..
i've recently begun c++ programming in linux.i'm using debian sarge (stable) and gcc 3.3.
the problem is that i cant use string variables in my program. whenever i declare a string variable with

string *variablename*

the compiler returns an error "variable string not defined"..

i've tried using both
#include <string> and
#include <string.h>
but none works..

help...
 
Josh said:
For c++ include iostream.h

you dont need iostream.h for 'string'.. that necessary for reading from and writing on the standards streams viz. using functions like cin, cout etc. :)
For using string, you just need to include the header viz #include <string> and use the namespace viz using namespace std;
 
@elendil....thanx..right now i am in my college..will try this out when i go home and post what happens...
just for curiosity..what does that extra statement mean??
 
its working..thanx m8:)

now one more thing..the program is really a novice one..
it is supposed to read each word in a string and print them out separately and then quit.

the code is..
Code:
#include<iostream.h>
#include<string.h>
using namespace std;
main()
{
string word;
while(cin>>word)
cout<<"\nthe word is "<<word<<"\n";
cout<<"no more words. ta ta";
}

but its not quitting automatically after the output. i'm having to hit ctrl+c.
whats wrong here?
 
The cause of the problem is the while statement. You seem to be confused with the return value of cin. cin returns an istream, which will NEVER be 0. So that loop will continue forever.

BTW try making that int main()

and at the end use either return 0; or exit(0);

As for "using namespace std" I would suggest you read Bjarne Stroustrup's book, any explanation given here will not suffice. Many compilers can work without it but gcc insists on it. Also drop the ".h" at the end of string.h and iostream.h

Simply say #include<string>

If you don't want to say "using namespace std" then preface every use of cin and cout with std:: ie. "std::cin>>x" etc.
 
just remove the while loop and try cin>>word; instead of while(cin>>word)
if you want to cin more than one string then make an array of strings like
Code:
int n;
string *word;
cout<<"Enter number of strings"<<endl;
cin>>n;
word=new string[n];
for(i=0;i<n;i++)
{
cin>>word[i];
cout<<"Word was "<<word[i]<<endl;
}
 
Back
Top