www.digitalmars.com         C & C++   DMDScript  

c++ - cin with a string

reply st <st_member pathlink.com> writes:
This compiles but does not execute:
//(code has been shortened on purpose)

#include <iostream.h>
#include <string>

string something;

int main()
{

cout << "Enter your name: ";
cin >> something;

}

This compiles and executes properly:

#include <iostream.h>
#include <string>

char something[40];

int main()
{

cout << "Enter your name: ";
cin >> something;

}

Why won't a string work with cin?
Mar 16 2003
parent reply Richard Grant <fractal clark.net> writes:
In article <b539un$1097$1 digitaldaemon.com>, st says...
This compiles but does not execute:
//(code has been shortened on purpose)

My guess is that you are using the older stream library since using stlport and this works as expected: #include <iostream> #include <string> int main() { std::string something; std::cin >> something; } But the real answer to your question is that it does not work because you do not have an extraction operator defined for istream and "string" in your environment. Richard
Mar 17 2003
parent "Jim Jennings" <jwjenn mindspring.com> writes:
"Richard Grant" <fractal clark.net> wrote in message
news:b54gjm$1qvp$1 digitaldaemon.com...
 In article <b539un$1097$1 digitaldaemon.com>, st says...
This compiles but does not execute:
//(code has been shortened on purpose)

My guess is that you are using the older stream library since using

 this works as expected:

 #include <iostream>
 #include <string>

 int main() {
 std::string something;
 std::cin >> something;
 }

 But the real answer to your question is that it does not work because you

 have an extraction operator defined for istream and "string" in your
 environment.

 Richard

If you want to enter more than one name, e.g., Joe Fauntleroy Blow, try: std::getline(std::cin, something);
Mar 17 2003