Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::cin input with spaces?

People also ask

Can CIN take spaces?

You can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.

How do you put a space between inputs in C++?

Whitespace in C++cout<<"Hello"; cout << "Hello"; cout << "Hello" ; cout << "Hello"; The exceptions where C++ compiler takes whitespace in consideration is inside quotes and for operator detection. So whenever you put in a string, c++ takes note of the whitespace.

How do you input a string with spaces?

Once the character is equal to New-line ('\n'), ^ (XOR Operator ) gives false to read the string. So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);


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

Use std::getline:

#include <string>
#include <iostream>

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.


You have to use cin.getline():

char input[100];
cin.getline(input,sizeof(input));

The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:

std::string s;
std::getline(std::cin >> std::ws, s);

Use :

getline(cin, input);

the function can be found in

#include <string>