216
#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?

5
  • 39
    You shouldn't edit your questions to ask new questions like that. The reason is that people have already given answers to your original question and now those answers seem out of context. If your original question has already been answered just start a new question to avoid confusion.
    – Pete
    Apr 30, 2011 at 1:26
  • It's apparent after a little examination, but could you please add a declaration for the variable library so that it's clear that it is of the type cd
    – chandsie
    Apr 30, 2011 at 1:30
  • there's good stuff here, no need to delete
    – dukevin
    Apr 30, 2011 at 2:24
  • 2
    In your update, you're trying to getline into an int. Of course that fails.
    – Ben Voigt
    Aug 28, 2013 at 18:38
  • You should probably know this by now (considering the age of this question) but you're really using structures and array wrong. You should have a structure with a single CDTitle, a single Artist and a single number_of_songs. Then have an array (or better yet a std::vector) of the structure. Mar 29, 2018 at 16:44

8 Answers 8

298

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.

7
  • 7
    I like this answer much better than the accepted one, because I don't need to specify a character length. Sep 7, 2018 at 19:35
  • 3
    @TheWanderer Indeed, that's a significant benefit. Sep 10, 2018 at 10:34
  • @LightnessRacesinOrbit, can you please help? This gives me an extra newline for no reason while printing my output. Jun 25, 2020 at 13:34
  • @AnshumanKumar I think getline may include the terminating newline in the string it returns. If so, it's up to you to delete it. Jul 16, 2020 at 16:50
  • 1
    I'm trying to achieve exactly what's been suggested and it doesn't work for me. It prints "Enter your name: Enter your favorite movie" ... Jun 5, 2022 at 11:32
127

You have to use cin.getline():

char input[100];
cin.getline(input,sizeof(input));
5
  • 9
    @Kevin Meh, it happens. C++ isn't exactly as intuitive as we would like it to be.
    – Pete
    Apr 30, 2011 at 0:54
  • 74
    Ew; why use char-buffers? It's 2011. Apr 30, 2011 at 2:03
  • 5
    And why not use cin.getline(input, sizeof(input));? Also, shouldn't you check the return status? Jun 14, 2013 at 23:32
  • 6
    @JonathanLeffler At the time this was written, this was the answer I had for the question that was originally asked (look at the first comment for the actual question and you will see that the context had changed due to an edit by the OP). Either way, if you feel the answer is that terrible, downvote it. I acknowledge that this may not be the "best" solution but it's a solution no less. Instead of asking why I didn't use something, you could tell us all why we should do it your way.
    – Pete
    Jun 14, 2013 at 23:50
  • 10
    Your answer is not terrible and doesn't need downvoting. I do think two small changes would improve it. Change 1 would use sizeof(input) in place of 100 in the call to cin.getline(); that would mean you can change the size of the input buffer and only need to change one line instead of two lines. Change 2 would be to test the return from cin.getline() by using, for example, if (!cin.getline(input, sizeof(input))) { ...handle EOF or error... } or something similar, to remind the OP that input operations, in particular, are vulnerable to unexpected behaviour. Other answers need this too. Jun 15, 2013 at 0:23
77

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);
3
  • 6
    I think this is the best answer so far. I can combine this with the std::cin>> on above.
    – Andra
    Oct 24, 2018 at 18:08
  • 2
    Best answer so far. When using std::getline(std::cin, s) I would get a very messy and I would say, interrupted input when waiting for inputs in a while/for loop. This option resolved my issue! Jan 8, 2020 at 20:27
  • 1
    Include sstream: #include <sstream>
    – GilbertS
    Feb 7, 2020 at 9:45
36

Use :

getline(cin, input);

the function can be found in

#include <string>
4
  • 3
    +1 This is the only answer that actually worked for me. The rest of the answers say to use cin.getline() but that just gave me an error saying the function doesn't exist.
    – blembo
    Dec 9, 2015 at 20:29
  • 10
    @blembo: Really? Because my answer, posted more than three years before this one, says the exact same thing (as opposed to what you claim it says). Jan 27, 2018 at 21:54
  • @blembo: And if cin.getline doesn't exist on your system, you have done something very wrong. Most likely you were passing the wrong arguments. Best not to blame others for your mistakes... Jan 27, 2018 at 21:55
  • @LightnessRacesinOrbit I understand how this answer can be viewed as a subset of your answer (content-wise). The problem mentioned in that comment might have been a consequence of the difference in presentation and the order of answers in this thread (wrt. the tick & votes). If a speed reader begins unsatisfied with the C-style getline, followed by a much longer answer of yours (though useful for focused readers), followed by another way of using getline, the reader may finally conclude that this answer is the better of them, which basically resembles yours, but in a concise manner. Feb 9, 2021 at 17:23
15

You want to use the .getline function in cin.

#include <iostream>
using namespace std;

int main () {
  char name[256], title[256];

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

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

  cout << name << "'s favourite movie is " << title;

  return 0;
}

Took the example from here. Check it out for more info and examples.

7
  • 13
    In fact, you rarely want to use member-getline. It's outmoded. Use free getline instead, which can be used with std::string. [BTW, cplusplus.com is not a recommended resource] Apr 30, 2011 at 2:05
  • 2
    @Tomalak Why is cplusplus.com not recommended? I use it all the time :P
    – dukevin
    Apr 30, 2011 at 3:20
  • 7
    @KevinDuke: The tutorials can be misleading and inaccurate, and the reference contains a multitude of errors. These are good resources. Apr 30, 2011 at 11:57
  • 1
    @NickSweeting: Yeah; use this instead. Apr 4, 2014 at 15:51
  • 2
    For documentation links, cppreference.com is an effective replacement for cplusplus.com (both are non-official paraphrases)
    – Ben Voigt
    Jul 10, 2014 at 23:02
6

How do I read a string from input?

You can read a single, whitespace terminated word with std::cin like this:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    cout << "Please enter a word:\n";

    string s;
    cin>>s;

    cout << "You entered " << s << '\n';
}

Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow. If you really need a whole line (and not just a single word) you can do this:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    cout << "Please enter a line:\n";

    string s;
    getline(cin,s);

    cout << "You entered " << s << '\n';
}
5

THE C WAY

You can use gets function found in cstdio(stdio.h in c):

#include<cstdio>
int main(){

char name[256];
gets(name); // for input
puts(name);// for printing 
}

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 in iostream itself.

#include<iostream>
#include<string>
using namespace std;
int main(){

char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
1
  • 12
    Very bad advice, gets is impossible to use safely. It's even been removed completely in C11.
    – Mat
    Jul 9, 2015 at 5:36
2

I rather use the following method to get the input:

#include <iostream>
#include <string>

using namespace std;

int main(void) {
    string name;

    cout << "Hello, Input your name please: ";
    getline(cin, name);

    return 0;
}

It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

Not the answer you're looking for? Browse other questions tagged or ask your own question.