views:

235

answers:

3

I know that for an integer, you can use:

int value;

I tried:

string str;

but Visual C++ gave me an error. How do I declare it without assigning a value, then using cin >> str later on to assign it?

+14  A: 
#include <string>
int main()
{
 std::string str;
 return 0;
}

Check this info on Namespaces by MSDN

AlexKR
I can also write "using namespace std; string str;" right? I read it here while googling (http://www.cprogramming.com/tutorial/string.html) but I thought since I already wrote "using namespace std;" below the "#include <iostream>" I did not have to re-write it.
Fabian
Also, if you find you're using std::string in your code a lot, `using std::string;` will help.
Bill
In general it's recommended to not use `using namespace std;` but to just pull in the parts of the std namespace that you'll actually use: `using std::string; using std::cout; using std::endl;`, for instance.
Bill
Fabian, you are right of course, you don't have to rewrite it
henle
Why won't this work? #include <iostring>#include <string>int main() { std::string str; cout << "Hi"; cin.get();}
Fabian
@Fabian, because it should be std::cout, std::cin
AlexKR
+1  A: 
#include <string>
using std::string;

int main() {
    string str;
    return 0;
}
Amro
A: 

Try the following:

#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::cin;

int main()
{
  string str;
  cout << "Enter a string: ";
  cin >> str;
  cout << "You entered: " << str;

  return 0;
}
Bill
What's the difference between iostring and iostream?
StackedCrooked
that'd be a typo. :P Thanks!
Bill