#include <string>
std::string input;
std::cin >> input;
The user wants to enter "Hello World". But cin
fails at the space between the two words. How can I make cin
take in the whole of Hello World
?
I'm actually doing this with structs and cin.getline
doesn't seem to work. Here's my code:
struct cd
{
std::string CDTitle[50];
std::string Artist[50];
int number_of_songs[50];
};
std::cin.getline(library.number_of_songs[libNumber], 250);
This yields an error. Any ideas?
You want to use the .getline function in cin.
Took the example from here. Check it out for more info and examples.
THE C WAY
You can use
gets
function found in cstdio(stdio.h in c):THE C++ WAY
gets
is removed in c++11.[Recommended]:You can use getline(cin,name) which is in
string.h
or cin.getline(name,256) which is iniostream
itself.You have to use
cin.getline()
:Use :
the function can be found in
It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".
Use
std::getline
:Note that this is not the same as
std::istream::getline
, which works with C-stylechar
buffers rather thanstd::string
s.Update
Your edited question bears little resemblance to the original.
You were trying to
getline
into anint
, not a string or character buffer. The formatting operations of streams only work withoperator<<
andoperator>>
. Either use one of them (and tweak accordingly for multi-word input), or usegetline
and lexically convert toint
after-the-fact.This is an old question but can someone tell me if my solution is incorrect: