This program's purpose is basically to get a character from a user and repeat it. There were a few things we had to do other than that in the program but that was the gist of it.
#include <iostream>
using namespace std;
int main(){
// Variable Declaration
int repeat;
char character;
// Prompt User for Repeat & Character
cout << "Character: ";
cin >> character;
cout << "Repeat: ";
cin >> repeat;
// Loop: Check if Repeat is Negative
while (repeat < 0) {
cout << "Repeat value cannot be negative." << endl;
cout << "Repeat: ";
cin >> repeat;
}
// Printing Characters According to Repeat Value
if (repeat == 0) {
cout << endl;
return 0;
} else {
for (int count = 0; count < repeat - 1; ++count) {
cout << character << " ";
}
cout << character;
}
// Newline after For loop
cout << endl;
// Inform Operating System (Successful)
return 0;
}
Basically I used an exit(0); in an if statement to exit out of the program like my professor wanted. He exclaimed Program execution: 7/7. All my test cases executed correctly. Good!
Source code: 2.5/3 Uninitialized: repeat, character
You have called exit to escape early. Do not do this. (Do not escape a loop early with any construct. You are using it to patch some sloppy code.)
Should I use a return rather than using exit? Why is this considered sloppy code? What are some other alternatives I could use?
I used return 0; rather than using exit(0);
exitis a blunt instrument that you should only use when you want the program to end as fast as possiblestd::cin. (okay,cin >> character;is hard to screw up, but what happened to the'\n'generated by pressing theEnterkey?)