Skipping getline (cin, stringvar);

In my program when I ask the users to enter a username, target (fake) and message, it skips over the user's entry for the message when I use getline (cin, message); I reference the function writer the second line in my main program, just after system("color 0A"); encase that helps at all. Please help. I feel like the answer is just right in front of me but I can't see it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <windows.h>
#include <fstream>
using namespace std;

void writer()
  {
  string username;
  string target;
  string message;
  
  cout << "Input Username: ";
  cin >> username;
  cout << "Input Target: ";
  cin >> target;
  cout << "Input Message: ";
  getline (cin, message);
  
  //Writter
  ofstream Writter;
  Writter.open ("message.txt");
  Writter << "To: " << target;
  Writter << endl;
  Writter << "From: " << username;
  Writter << endl;
  Writter << endl;
  Writter << message;
  Writter << endl;
  Writter << endl;
  Writter << "--------------";
  Writter << endl;
  Writter << "END OF MESSAGE";
  Writter << endl;
  Writter << "-----------";
  Writter.close();
  }
Last edited on
It's a common problem, but it's not necessarily obvious.
See the answers to this thread for an explanation and solution: http://www.cplusplus.com/forum/beginner/60520/
I've read the article you suggested that I read but I am still confused. Can you point out where I goofed up on my coding and how to fix it?
Nevermind, I figured out my mistake. I used cin.ignore(); before getline (cin, message); It helped me but then I went to add another string and did the same but it didn't work so I removed the second cin.ignore() and everything worked flawlessly. Thanks for the feedback. Your suggested article sure did send me in the right direction.
The >> operator does not remove the end-of-line character that you enter when you press RETURN. So the following std::getline() reads it rather than moving to the next input. You need to skip over the end-of-line character. There are a few ways to do this. For example:
 
 cin >> target >> std::ws; // skip over end-of-line (std::ws = whitespace)  
Topic archived. No new replies allowed.