Junk Input Causes the Program to Ignore "cin.ignore(1000, '\n');"

I'm having trouble with this section my code and am hoping that you can help me diagnose and solve the problem. I'm not sure if it makes a difference, but I compile and run my code in Cygwin.

The problem:
At run time when the program asks for the user input I can input somethimg like: "Guybrush Threepwood Throe" and the code will run just fine, but if I type the same thing and then use the left arrow button to move the cursor back over the input to make a correction (for instance to change the third word of the input from "Throe" to "Three"), the program will ignore (or seem to ignore) all of my "cin.ignore(1000, '\n');" and "cin.getline(input1, 31, '\n');" commands. I'm aware that you're not technically supposed to use the arrow keys in Cygwin, but I'm trying to make my code fool-proof.

Why does this happen, and assuming the user will eventually use those arrow keys, how can I prevent the undesired side-effects?

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
38
39
40
41
42
43
44
45
#include <cstdlib>
#include <iostream>
using namespace std;

int main ()
{
  char input1[31];
  char default1[31] = "                              ";
  int success = 0;
  int tries = 0;
  while ((success == 0) && (tries < 4))
  {
     cout << "[By what name shall you be known? Max: 30 Characters]" <<   endl;
     cout << ":" << endl;
  // Point of possible conflict follows immediately
     cin.getline(input1, 31, '\n');
     if (((input1[0] > 64) && (input1[0] < 91)) || ((input1[0] > 96) && (input1[0] < 123))) 
        success = 1; // Success = 1 if input1 starts with a letter.
     else
     {
        cout << "What kind of name doesn't begin with a letter?" << endl;
        cout << "(Type a name that starts with a letter.)" << endl;
        tries++;
     }
  }

  if (tries >= 4)
  {
     char guybrush[31] = "Guybrush";
     strcpy (input1, guybrush);
     cout << "Fine. I'm going to assume your name is Guybrush." << endl;
  }


  cout << "Some text here..." << endl;
  cin.ignore(1000, '\n');     // Used as a pause function
  cout << "Some more text here..." << endl;
  cin.ignore(1000, '\n');

  strcpy (input1, default1);
  cout << "Input command." << endl;
  cout << ":";
  cin.getline(input1, 31, '\n');
  return 0;
}


Thank you for your input.
Last edited on
Thanks to the people at DaniWeb.com for helping me with this problem, which I solved using the following code.

1
2
3
4
5
6
7
8
void clear (ios::iostate flags = ios::goodbit);

if ( cin.fail() )
{
  cout << "Failed." << endl;
  cout << "Please do not use the arrow keys." << endl;
  cin.clear();
}


If you're looking for a responsive, helpful and friendly programming forum, DaniWeb seems to be the place to be.

Here's a link to the thread.
http://www.daniweb.com/forums/post708130.html
Last edited on
I would've just used getline(cin, string);.
Topic archived. No new replies allowed.