Robert J
Robert J

Reputation: 978

cin.ignore() enter twice to get one pause

Problem statement:

I am just learning the syntax for C++ and for some reason I have to enter cin.ignore(); twice in my script to get my program to pause once. Note that line 48 is commented out for troubleshooting purposes.

Code:

1   // Lab 3 Exercise 1
2   // Input Using cin >>
3   //
4   // Program by: Robert J
5   
6   #include <iostream>
7   #include <cmath>
8   #include <string>
9   using namespace std;
10  
11  // creating functions
12  float delta_miles(float end_mileage, float start_mileage){
13      return end_mileage - start_mileage;
14  };
15  
16  float mileage(float end_mileage, float start_mileage, float travel_time){
17      return (end_mileage - start_mileage) / travel_time;
18  };
19  
20  float mileconv(float miles){
21      // There are 1604 m in a mile
22      return miles * 1.604;
23  };
24  
25  int main(){
26      // Variable definitions
27      float milestart, milesend, hours, total_miles, mph;   // floatValue is of type float
28  
29      printf("Enter the starting mileage (miles): " );
30      cin >> milestart;
31      printf("Enter the ending mileage (miles): " );
32      cin >> milesend;
33      printf("Enter the number of hours traveled (2.25 horus = 2 horus 15 minutes): " );
34      cin >> hours;
35  
36      // Calculations
37      total_miles = delta_miles(milesend, milestart);
38      mph = mileage(milesend, milestart, hours);
39  
40      // Output
41      printf("\n"); // seperator that is easy to find
42  
43      printf("Total miles traveled:\t%f\n", total_miles);
44      printf("Miles per Hour: \t%f\n", mph);
45      printf("Total kilometers:\t%f\n", mileconv(total_miles) );
46      printf("Kilometers/Hour:\t%f\n", mileconv(mph) );
47  
48  //  cin.ignore();
49      cin.ignore();
50      // Exit code:
51      return 0;
52  }

Attempted solutions:

Questions:

Does anyone see what am doing wrong here?

Thanks in advance all.

Upvotes: 2

Views: 742

Answers (2)

kmdreko
kmdreko

Reputation: 59942

David Schwartz answered your why but a solution to your problem, pausing for at the end of the program, can be solved by this (which is what I always do in situations like this)

cin.get();

get() retrieves a character from the stream but can only do so when it's flushed by the enter key

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182753

It is because of this line of code:

cin >> hours;

This reads the number of hours, but not the enter you pressed after it. So your first cin.ignore() call ignores that enter key. Only your second one causes a pause.

If you want to read lines, use a function that reads lines. Don't use a function that reads a number and expect it to read a line.

Upvotes: 1

Related Questions