cin.ignore() not working

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
#include <iostream>
#include <time.h>
#include <string>
using namespace std;


int main ()
{
  time_t start,end;
  string name;
  double dif;

  cout << "This program will measure how long it takes you to type your name.";
  cout << endl << "Press [ENTER] to start...";
  cin.ignore(256, '\n'); //I use this to pause my program, instead of using system("PAUSE").  It works here.
  time (&start);
  cout << "Please, enter your name: ";
  cin >> name;
  time (&end);
  dif = difftime(end, start);
  cout << "Hello, " << name << ". It took you " << dif 
       << " seconds to type your name." << endl << endl;
  cout << endl << "Press [ENTER] to start...";
  cin.ignore(256, '\n');  //But it doesn't work here.  Why?
  return (0);
}

I use cin.ignore(256, '\n'); to pause my programs, because everyone always says that system("PAUSE") is bad programming practice, and can actually be a security risk. So, why is it that my program pauses the first time i use cin.ignore() but not the last time I use it? How can I fix this problem?
When you are getting the input for the name use this:
getline(cin, name);
Instead of cin >> name.

That way you are not leaving anything in the stream for the program to read.
Okay. But what if i had a bigger program and I had to use my pause function more than once. Is there a way to clear the stream so that I can pause more than just once?
Basically, if you're workign with string objects use eker's example: getline(cin, name);

If your using c-strings you need to use cin.ignore(); // by defualt it takes \n as an argument so that you ignore any newline characters left in the stream.

Personally, at the end of a program I use [cin.get();[/code] to puase my programs but this is only because I just do it as short hand. The way you should use is:
std::cin.ignore(std::numeric_limits ::max(), '\n');
Topic archived. No new replies allowed.