By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,260 Members | 1,352 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,260 IT Pros & Developers. It's quick & easy.

Program isn't stopping for cin

P: 2
Hi, I'm new to C++ and thought I would write a simple journal application for myself to help learn how to use the language.
Anyway here is the source for the program
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. using namespace std;
  6. int main () 
  7. {
  8.     string awnser;
  9.     cout << "Welcome to Journal, would you like to add a entry to your journal?(1=yes, 2=no)\n";
  10.     cin >> awnser;
  11.     if (awnser == "1")
  12.     {
  13.         string entry;
  14.         cout << "Ok, type what you want to be added to your journal.\n";
  15.         getline(cin,entry);
  16.         ofstream journal ("journal.txt", ios::app);
  17.         /* ("journal.txt", ios::app);*/
  18.         journal << "\n" << entry;
  19.         journal.close();
  20.     }
  21.     else
  22.     {
  23.         cout << "Ok then, have a nice day\n";
  24.     }
  26.     return 0;
  27. }
Now when I compile this program there is no error but when I run it the program dosen't stop for cin, it just ends after it says "Ok, type into you ~~~"
Anyone know whats wrong?
Nov 6 '06 #1
Share this Question
Share on Google+
2 Replies

Expert 2.5K+
P: 3,652
I know exactly what went wrong - it's a weird little thing with cin.

When you use getline, the function does not ignore previous input (such as your cin >> awnser statement above). Thus, it has read whatever you entered for the previous prompt for the getline.

In order to bypass this, type in

Expand|Select|Wrap|Line Numbers
  1. cin.ignore(100, '\n');
right before your getline. This will tell cin to get rid of 100 characters or all characters until the newline character (whichever occurs first). Then your getline will wait for further input.
Nov 6 '06 #2

P: 2
Ah, thank you verry much, that worked perfectly, and now I know about ignore()
: )
Nov 6 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.