While loop to allow the User to run the program more than once.

I've written a program for my c++ class that is attached. Everything works fine except the fact that I have to use a While loop to allow the User to run the program more than once. Using a sentinel value of “Y” and prompting the User to enter a “Y” if they wish to continue. The problem is no matter how I write the While loop and no matter where I put it in the program I get error messages. Any help is appreciated.

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
46
47
48
  #include <iostream>

using namespace std;

int timeDifference(int, int);
int endtime;
int time;
int main()



{
    int start, end;

    cout << "Please input your start time in military time(example: 830=2030): ";  //request for user to input start time
    cin >> start;
    cout << "Please input your end time: ";                                      //request for user to input end time
    cin >> end;

bool endtime(int time);
{
	if(end > start)
 cout << "Your elapsed time is " << timeDifference(start, end) << " minutes."<<endl;   //result of calculations displayed; 
	else if (start > end) 
		cout <<"Error - End time must be greater than start time." <<endl; 
}

    return 0;
}

int minutes(int time)         //function to convert time to total minutes
{

    int hours = time/100;        //separation of time to hours
    int minutes = time%100;      //separation of minutes
    return hours*60 + minutes;         //calculation to return total minutes of hours and minutes

}
int timeDifference(int s, int e)             //function to subtract start and end time
{
    int begin = minutes(s);  //declaration of start and end times
    int end = minutes(e);
    return end - begin;                   //calculation to return minute difference
}



Last edited on
Lets beautify your whitespace:
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
#include <iostream>

using namespace std;

int timeDifference(int, int); // function declaration
int endtime; // global variable, never used
int time; // global variable, never used

int main()
{
    int start, end;
    cout << "Please input your start time in military time(example: 830=2030): ";
    cin >> start;
    cout << "Please input your end time: ";
    cin >> end;

    bool endtime(int time); // function declaration, never called

    { // additional local scope
      if (end > start)
        cout << "Your elapsed time is " << timeDifference(start, end) << " minutes."<<endl;
      else if (start > end)
        cout <<"Error - End time must be greater than start time." <<endl;
      else ; // end==start, but you say nothing
    }

    return 0;
}

int minutes(int time) // helper function
{
    int hours = time/100;
    int minutes = time%100;
    return hours*60 + minutes;
}

int timeDifference(int s, int e)
{
    int begin = minutes(s);
    int end = minutes(e);
    return end - begin;
}

Lets drop unused bits (and some):
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
#include <iostream>

using namespace std;

int timeDifference(int, int); // function declaration

int main()
{
    int start, end;
    cout << "Please input your start time in military time(example: 830=2030): ";
    cin >> start;
    cout << "Please input your end time: ";
    cin >> end;

    if (end > start)
      cout << "Your elapsed time is " << timeDifference(start, end) << " minutes."<<endl;
    else
      cout <<"Error - End time must be greater than start time." <<endl;

    return 0;
}

int minutes(int time) // helper function
{
    int hours = time/100;
    int minutes = time%100;
    return hours*60 + minutes;
}

int timeDifference(int s, int e)
{
    return minutes(e) - minutes(s);
}


The question is, what do you want to repeat?

Lets say that there are
1
2
// important
// statements 

and you want to repeat them 5 times. With a loop:
1
2
3
4
5
6
7
int count=0;
do {
  // important
  // statements

  ++count;
} while ( count < 5 );

But in your case it was not "5 times". You have to replace the increment with user input and update the condition.

You "have to use while, not do while"?
The only difference is that the condition is earlier and therefore it has to be initially true.
keskiverto, thank you for your help. I've cleaned up the code, I have a bad habit of leaving bits and pieces of prior versions in my code behind. This is the current version:

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
#include <iostream>

using namespace std;

int timeDifference(int, int); // function declaration
char runAgain{ 'Y' };
int main()
{
    int start, end;
    cout << "Please input your start time in military time(example: 830=2030): ";
    cin >> start;
    cout << "Please input your end time: ";
    cin >> end;

    if (end > start)
      cout << "Your elapsed time is " << timeDifference(start, end) << " minutes."<<endl;
    else
      cout <<"Error - End time must be greater than start time." <<endl;

while (runAgain == 'y' || runAgain == 'Y');//program runs again if y, Y entered
{
	int start, end;
    cout << "Please input your start time in military time(example: 830=2030): ";
    cin >> start;
    cout << "Please input your end time: ";
    cin >> end;
}
    return 0;
}

int minutes(int time) // helper function
{
    int hours = time/100;
    int minutes = time%100;
    return hours*60 + minutes;
}

int timeDifference(int s, int e)
{
    return minutes(e) - minutes(s);
}


I think I've got the "while" written correctly but it seems that no matter where I place it I get an error message. For example for this current version I get the message,

"6 14 [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11."


Also the
1
2
3
4
5
6
7
8

bool endtime(int time);
{
	if(end > start)
 cout << "Your elapsed time is " << timeDifference(start, end) << " minutes."<<endl;   //result of calculations displayed; 
	else if (start > end) 
		cout <<"Error - End time must be greater than start time." <<endl; 
}


was an attempt at completing this part of the instructions,

"A function that returns a Boolean value of true if the ending time is greater than the beginning time and a value of false if the ending time is less than the beginning time.
Use this function to error check the input.
If the function returns a true to main then calculate the elapsed time.
If the function returns a false then print out an error message stating that the beginning time must be less than the ending time."

I assumed I had that part correct and didn't mention it in my original post.

This is a function declaration:
bool endtime(int time) ;
You see the semicolon, don't you?

This is an implementation of a function:
1
2
3
4
5
6
7
bool endtime(int time) // no semicolon here
{
  if (end > start )
    cout << timeDifference(start, end) << endl;
  else if (start > end) 
    cout << "Error\n"; 
}


It is illegal to implement a function inside another function. You almost had:
1
2
3
4
5
6
7
8
9
int main()
{

  bool func(int time) // error: function inside body of another function
  {
    return time < 42;
  }

}


A function that returns a Boolean value
1
2
3
4
5
6
7
bool endtime(int time)
{
  if (end > start )
    cout << timeDifference(start, end) << endl;
  else if (start > end) 
    cout << "Error\n";
} // where here was a 'return' statement? 

A function that promises to return a value must do so too.


Your indentation is not consistent. It is hard to see that the loop is inside the main(), because it is not indented like other statements in the same scope.


Why is the 'runAgain' a global variable? It will be used only inside the main(), just like the 'end' and 'start'.

You don't modify the runAgain inside the loop. If it does not change there, then the loop will repeat forever.


6 14 [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11.

A warning, not an error.
You do use brace initializer on line 6. Brace initializer was added in C++11 standard.
Your compiler does not support C++11 by default, but it can, if you ask for it.
You ask by adding -std=c++11 to compiler's command line options.
I went ahead and re-wrote the code and if I separate this section:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
using namespace std;
int main()
{ 
char again = 'Y';
while (again == 'y' || again == 'Y') {
  bool endtime(int time);
     int start, end;
         cout << "Please input your start time in military time(example: 830=2030): ";
         cin >> start;
         cout << "Please input your end time: ";
         cin >> end;
         cout << "\n\nrun the program again (y/n)? " ;
         cin >> again ;
  }
  return 0; 
}

and run it alone it runs fine but as soon as I add the rest of the code I get the error messages:
"32 1 [Error] a function-definition is not allowed here before '{' token
39 1 [Error] a function-definition is not allowed here before '{' token"

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
#include <iostream>
#include <string>
using namespace std;
int timeDifference(int, int); // function declaration
int start;
int end;
int main()
{ 
char again = 'Y';
while (again == 'y' || again == 'Y') 
{
  bool endtime(int time);
     int start, end;
         cout << "Please input your start time in military time(example: 830=2030): ";
         cin >> start;
         cout << "Please input your end time: ";
         cin >> end;
         cout << "\n\nrun the program again (y/n)? " ;
         cin >> again ;
  
}
{
	if (end > start)
        cout << "Your elapsed time is " << timeDifference(start, end) << " minutes."<<endl;
        else
        cout <<"Error - End time must be greater than start time." <<endl;
  }  
  return 0; 

int minutes(int time) // helper function
{
    int hours = time/100;
    int minutes = time%100;
    return hours*60 + minutes;
}

int timeDifference(int s, int e)
{
    return minutes(e) - minutes(s);
}
}


I'm lost as to what to do next.
Last edited on
but as soon as I add the rest of the code I get the error messages:
"32 1 [Error] a function-definition is not allowed here before '{' token
39 1 [Error] a function-definition is not allowed here before '{' token"

Are you sure? Because what I get is:
In function 'int main()':
main.cpp:23:13: error: reference to 'end' is ambiguous
         if (end > start)
             ^~~
[omissis]
note: candidates are:
'template<class _Tp> const _Tp* std::end(const std::valarray<_Tp>&)'
   template<typename _Tp> const _Tp* end(const valarray<_Tp>&);
                                     ^~~
'template<class _Tp> _Tp* std::end(std::valarray<_Tp>&)'
   template<typename _Tp> _Tp* end(valarray<_Tp>&);
                               ^~~
'template<class _Tp, long long unsigned int _Nm> constexpr _Tp* std::end(_Tp (&)[_Nm])'
     end(_Tp (&__arr)[_Nm])
     ^~~
'template<class _Container> constexpr decltype (__cont.end()) std::end(const _Container&)'
     end(const _Container& __cont) -> decltype(__cont.end())
     ^~~
'template<class _Container> constexpr decltype (__cont.end()) std::end(_Container&)'
     end(_Container& __cont) -> decltype(__cont.end())
     ^~~
'template<class _Tp> constexpr const _Tp* std::end(std::initializer_list<_Tp>)'
     end(initializer_list<_Tp> __ils) noexcept
     ^~~
main.cpp:6:5: note:                 'int end'
 int end;
     ^~~
main.cpp:24:66: error: reference to 'end' is ambiguous
         cout << "Your elapsed time is " << timeDifference(start, end) << " minutes."<<endl;
                                                                  ^~~
candidates are:
'template<class _Tp> const _Tp* std::end(const std::valarray<_Tp>&)'
   template<typename _Tp> const _Tp* end(const valarray<_Tp>&);
                                     ^~~
'template<class _Tp> _Tp* std::end(std::valarray<_Tp>&)'
   template<typename _Tp> _Tp* end(valarray<_Tp>&);
                               ^~~
'template<class _Tp, long long unsigned int _Nm> constexpr _Tp* std::end(_Tp (&)[_Nm])'
     end(_Tp (&__arr)[_Nm])
     ^~~
'template<class _Container> constexpr decltype (__cont.end()) std::end(const _Container&)'
     end(const _Container& __cont) -> decltype(__cont.end())
     ^~~
'template<class _Container> constexpr decltype (__cont.end()) std::end(_Container&)'
     end(_Container& __cont) -> decltype(__cont.end())
     ^~~
'template<class _Tp> constexpr const _Tp* std::end(std::initializer_list<_Tp>)'
     end(initializer_list<_Tp> __ils) noexcept
     ^~~
main.cpp:6:5: note:                 'int end'
 int end;
     ^~~
main.cpp:31:5: error: a function-definition is not allowed here before '{' token
     {
     ^
main.cpp:38:5: error: a function-definition is not allowed here before '{' token
     {
     ^

Two of the above errors can be avoided simply NOT introducing the entire std namespace.
About the last two, just keep your code indented and they won’t occur again.
Look at your code from line 28 on. Is there a ‘}’ after return 0;?
Do the following braces match? Can’t you spot an extra brace after return minutes(e) - minutes(s);?
Enoizat, thanks for your help but unfortunately the prof. in this class wants us to use std namespace in this way. I did notice the extra bracket and removed that but even with dealing with that and dealing with the indenting I get the same error message.
If you must have using namespace std; then you need to change your variable end to some other name. Let's call it stop.

REgarding the original problem, try this:
1. Change main() to doOnce()
2. Add a new main() function that just calls doOnce()
3. Get rid of all attempts to loop inside doOnce
4. The program is now designed to run just one time. Get this working.
5. Once it's working one time, add code to main() to call doOnce inside a loop.

Below is your most recent attempt with "end" changed to "stop" and main changed to doOnce. I've indented it to reflect your original block structure. You should be able to see that functions minutes() and timeDifference() are mistakenly inside doOnce() so you need to pull them outside.
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
46
47
48
49
#include <iostream>
#include <string>
using namespace std;
int timeDifference(int, int);	// function declaration
int start;
int stop;
int
doOnce()
{
    char again = 'Y';
    while (again == 'y' || again == 'Y') {
	bool endtime(int time);
	int start, stop;
	cout << "Please input your start time in military time(example: 830=2030): ";
	cin >> start;
	cout << "Please input your end time: ";
	cin >> stop;
	cout << "\n\nrun the program again (y/n)? ";
	cin >> again;

    }
    {
	if (stop > start)
	    cout << "Your elapsed time is " << timeDifference(start,
							      stop) << " minutes." <<
		endl;
	else
	    cout << "Error - Stop time must be greater than start time." << endl;
    }
    return 0;

    int minutes(int time)	// helper function
    {
	int hours = time / 100;
	int minutes = time % 100;
	return hours * 60 + minutes;
    }

    int timeDifference(int s, int e)
    {
	return minutes(e) - minutes(s);
    }
}

int
main()
{
    doOnce();
}

Topic archived. No new replies allowed.