-
Is this good style?
Is the way I used a while loop good style or should it be avoided?
Code:
#include <iostream>
using namespace std;
int main(void){
int n;
while(std::cout << "Enter the number of lines (e to quit): " && std::cin >> n){
for(int i = 0; i <= n; ++i){
for(int k = 0; k < n - i; ++k)
std::cout << " ";
for(int m = 1; m < i * 2; ++m)
std::cout << "*";
std::cout << endl;
}
} return EXIT_SUCCESS;
}
-
Style is really not good nor bad, rather personal.
I've never seen anyone && two streams together in a condition, but have no trouble understanding what it means, and it does actually condense the code, so its not really a bad idea in that case. I would have written the code like this
Code:
#include <iostream>
using namespace std;
int main(void){
int n;
while(std::cout << "Enter the number of lines (e to quit): " && std::cin >> n){
for(int i = 0; i <= n; ++i){
// if no braces, put it on the same line
for(int k = 0; k < n - i; ++k) std::cout << " ";
// if using braces, put it on a different line
for(int m = 1; m < i * 2; ++m) {
std::cout << "*";
}
std::cout << endl;
}
} // no code after closing bracket
return EXIT_SUCCESS;
}
-
>Is the way I used a while loop good style or should it be avoided?
It's fine if all you are doing is this, but if you are obtaining any input after the while loop then you'll have to clear the stream state.
-
You don't need std::cout or std::cin since you included using namespace std;. Just use cout and cin.
Alternatively, instead of using the whole namespace std, you can declare using std::cout and using std::cin in place of using namespace std, save a bit of space. Kind of a personal choice there.
-
How would I clear the stream state? cin.clear()?
-
>How would I clear the stream state? cin.clear()?
Yes, and then a cin.ignore() to discard the bad input.