PDA

View Full Version : C++: cin.getLine -> not found



Ben Sprinkle
December 19th, 2006, 04:31 PM
Guys, I have a program that uses a string, why won't this work?


#include <iostream>

using namespace std;

int main() {
char c[20];
cin.getLine(c, 20, '\n');
}

Shouldn't that work? It says getLine not found in cin.

lnostdal
December 19th, 2006, 08:10 PM
Guys, I have a program that uses a string, why won't this work?


#include <iostream>

using namespace std;

int main() {
char c[20];
cin.getLine(c, 20, '\n');
}

Shouldn't that work? It says getLine not found in cin.




lars@ibmr52:~$ cat blah.cpp
#include <iostream>
#include <string>

using namespace std;

int main()
{
string s;
getline(cin, s);
cout << "you typed: " << s << endl;
return 0;
}
lars@ibmr52:~$ g++ -Wall -g blah.cpp -o blah && ./blah
Hello?
you typed: Hello?

Ben Sprinkle
December 19th, 2006, 08:18 PM
Thanks, do you know how to clear cin? cin.clear(); doesn't do it. I need cin to = "".

slavik
December 19th, 2006, 09:45 PM
cin is an istream type ...

Ben Sprinkle
December 20th, 2006, 04:03 AM
What's that mean?
How do I clear it?

slavik
December 20th, 2006, 06:12 PM
cin is an istream, an istream type is for input streams, which is ways to get input ...

cin is defined to be the standard input.

when you do cin>>var; it will check the type of var and read input into it. since you can't really flush the input buffer, after reading a variable, you can read char by char until EOF is returned ...

Ben Sprinkle
December 20th, 2006, 07:26 PM
How?
Give me an example to clear it please. :)

po0f
December 20th, 2006, 09:21 PM
Goat Spirit,

If you're using C++, why aren't you using std::string? And the following code behaves the way you would expect it to:

#include <iostream>
#include <string>

int main() {
std::string s;
std::cin >> s;

return 0;
}

getline() by default uses '\n' as a delimiter character, but I really don't know if it is taken out of the stream or discarded. I have always used "std::cin >> variable" to get input, which works.

lnostdal
December 20th, 2006, 09:30 PM
Goat Spirit,

If you're using C++, why aren't you using std::string? And the following code behaves the way you would expect it to:

#include <iostream>
#include <string>

int main() {
std::string s;
std::cin >> s;

return 0;
}

getline() by default uses '\n' as a delimiter character, but I really don't know if it is taken out of the stream or discarded. I have always used "std::cin >> variable" to get input, which works.

Try reading in both your first and surname in one go using cin >> variable.

po0f
December 20th, 2006, 11:37 PM
lnostdal,

Goat Spirit was just trying to read in one variable, so I posted an example that did the same. I know that after the space, no more input will be read in, if that's your point.

Ben Sprinkle
December 21st, 2006, 05:28 AM
Thanks all.