std::cin input with spaces?

lemon picture lemon · Apr 30, 2011 · Viewed 528.9k times · Source
#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?

Answer

Lightness Races in Orbit picture Lightness Races in Orbit · Apr 30, 2011

It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".

Use std::getline:

int main()
{
   std::string name, title;

   std::cout << "Enter your name: ";
   std::getline(std::cin, name);

   std::cout << "Enter your favourite movie: ";
   std::getline(std::cin, title);

   std::cout << name << "'s favourite movie is " << title;
}

Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.

Update

Your edited question bears little resemblance to the original.

You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.