Click to See Complete Forum and Search --> : [RESOLVED] cin >> string
Rick Bull
Sep 13th, 2002, 12:11 PM
I haven't done much with C++ and even less with string.h. I'm trying to get user input into a string, how do I do it? Again here's what I have:
void go()
{
cout << "URI: ";
string uri;
cin >> uri;
}
The Hobo
Sep 13th, 2002, 02:30 PM
What doesn't work for you?
If your string is going to have spaces in it, you're probably going to need to use cin.getline(), but that doesn't work directly with the string header, so...it's been awhile.
Rick Bull
Sep 13th, 2002, 02:46 PM
It's giving me an error about string being undeclared, so that means it's not in the string header, right? As you can tell, I don't know what I'm doing here :D
The Hobo
Sep 13th, 2002, 02:57 PM
How are you including the header? I do:
#include <iostream>
#include <string>
using namespace std;
I've seen other people do <iostream.h> and <string.h>, but this is how I've always done it.
wey97
Sep 13th, 2002, 03:05 PM
try this:
#include <string>
#include <iostream>
using namespace std;
void main(){
string str;
char c;
while(!cin.eof()){
c = cin.get();
str += c;
}
cout << str << endl;
}
end of file is ^Z (control-Z)
or you could use a newline char instead.
#include <string>
#include <iostream>
using namespace std;
void main(){
string str;
char c;
while(c != '\n'){
c = cin.get();
str += c;
}
cout << str << endl;
}
You always need to use standard headers.
#include <string>
#include <iostream>
using namespace std;
Rick Bull
Sep 13th, 2002, 03:24 PM
Thanks guys. I'll try that and see if it works. Although I've found with MS Visual C++ that if I use the use namespace std and miss of the .h in the includes it doesn't compile :confused: I think VC is a bit ****, because it work in Dev C++ OK.
Rick Bull
Sep 13th, 2002, 03:37 PM
I got it to work. I think it's because I was putting .h at the end and adding using namespace std. It seems to be OK now I took off the .h bit.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.