Do While Loop Problems

I don't understand why my Do While loop skips over the input the second time round?

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 <iostream> 
#include <cstring>
#include <cstdlib> 
#include <string>

using namespace std; 

//prototype
string reverseInput(string *);

int main ()
{
//variable    
string input;  
char ans;

//do while 
 do
{     
     cout<<"Please input anything you would like to see backwards."<<endl;
     getline(cin,input);//cin input
     input = reverseInput(&input); //call reverse function
     cout << input << endl; //cout reverse input
     cout<<"Try again?"<<endl;
     cin>> ans;
}

while (ans!='y');

    system ("PAUSE");
    return EXIT_SUCCESS; 
}

//reverse function
string reverseInput (string *strPtr) 
{ 
  string result="";
    for (int i=0; i<(*strPtr).length( ); i++)  
  { //get length 
   result = (*strPtr)[i] + result ; //reverse order
  } 
  return result; 
} 

I don't understand why my Do While loop skips over the input the second time round?


there is a newline left in the input stream from the user pressing enter
1
2
cin>> ans;
cin.ignore(); //<<---------add this 
Yes! I even told myself not to forget that at some point. Thank you very much!
Topic archived. No new replies allowed.