Skip to main content
GameDev.net gamedev.net
🔒 Locked

cin.getlin ?

Started by Kais0n Jul 13, 2004 at 4:28 AM 3 replies 1.5k views
Original Post
Kais0n
Kais0n
Hi, iv got a problem i want usa a c++ String for input. but i cant use cin as it stops at the first blank i wanted to use cin.get() or cin.getline() both isnt working. DEV C++ tells me i cant use a string... but if i rememer right it should. Am i wrong? can anyone help me on this?
abd9e4790f
abd9e4790f
Hmmm...

I tend to use the old C gets() and puts() IO functions when dealing with strings.

But if you prefer getline() then here is an example:

#include <string>#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){	string s1;	cout << "Enter a sentence (use <enter> as the delimiter): ";	getline( cin , s1 , '\n');	cout << "You entered: " << s1 << endl;	system( "PAUSE" );	return 0;}


getline():
_Istr
The input stream from which a string is to be extracted.
_Str
The string into which are read the characters from the input stream.
_Delim
The line delimiter.

So therefore, give it an input stream, a place to put the characters, and a character to stop reading input.
lshadow
lshadow
getline uses a char*, so it will be able to use the standard string. If you say what you want getline for I might be able to recommend something else (but getline might be the best option, I don't know).
Working on: DoP
pi_equals_3
pi_equals_3
DIRECTXMEN has the answer. Here's what's going on...

cin.getline is a function inside the input stream class. For whatever reason, there is no cin.getline which is overloaded to input strings.

This was a potential problem, because just as many people will want to input a line into a string as will want to input a line into a char*.

The solution is a function, also named getline, in the same file as string. It's used like this.

#include <iostream>#include <string>using namespace std;void main(){  string input;    cout << "Enter your name: ";  getline(cin, input);  cout << "Your name is " << input;}


the first parameter of getline is the stream to pull input from, which is the cin stream in this case. This must be a parameter because the string version of getline is declared on its own, outside cin's class.

The second parameter is the string where the input will be stored.

And the third is an optional parameter for the delimiter.
This is '\n' by default, so it will read until it hits a new line.
Kais0n
Kais0n
thx a lot this will solve my problme :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.