222
#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
  • 40
    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. Commented 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 Commented Apr 30, 2011 at 1:30
  • there's good stuff here, no need to delete Commented Apr 30, 2011 at 2:24
  • 2
    In your update, you're trying to getline into an int. Of course that fails. Commented 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. Commented Mar 29, 2018 at 16:44

8 Answers 8

308

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I like this answer much better than the accepted one, because I don't need to specify a character length.
@TheWanderer Indeed, that's a significant benefit.
@LightnessRacesinOrbit, can you please help? This gives me an extra newline for no reason while printing my output.
@AnshumanKumar I think getline may include the terminating newline in the string it returns. If so, it's up to you to delete it.
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" ...
|
128

You have to use cin.getline():

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

5 Comments

@Kevin Meh, it happens. C++ isn't exactly as intuitive as we would like it to be.
Ew; why use char-buffers? It's 2011.
And why not use cin.getline(input, sizeof(input));? Also, shouldn't you check the return status?
@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.
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.
80

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 Comments

I think this is the best answer so far. I can combine this with the std::cin>> on above.
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!
Include sstream: #include <sstream>
37

Use :

getline(cin, input);

the function can be found in

#include <string>

4 Comments

+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: 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).
@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...
@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.
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 Comments

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]
@Tomalak Why is cplusplus.com not recommended? I use it all the time :P
@KevinDuke: The tutorials can be misleading and inaccurate, and the reference contains a multitude of errors. These are good resources.
@NickSweeting: Yeah; use this instead.
For documentation links, cppreference.com is an effective replacement for cplusplus.com (both are non-official paraphrases)
|
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';
}

Comments

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 Comment

Very bad advice, gets is impossible to use safely. It's even been removed completely in C11.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.