> 1. Should a C++ beginner be able to do this problem?
> Because at less for my case, I have not seen "stuff" you use in the code
Yes. A beginner could assume that input would always succeed; that there is no badly formed line in the input.
> 2. Is it possible to make a working program, without using the "stuff" I mentioned in point 1
Yes, assuming that all input to the program is clean. Your earlier code, modified to continue to consume the remaining numbers in the current data set (after a non-unique number is encountered) would do.
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>
#include <vector>
// using namespace std;
int main() {
int sequence_size;
while (std::cin >> sequence_size) {
std::vector <int> already_seen (sequence_size+1);
bool loop = true;
// for (int i = 0; i < sequence_size and loop; ++i) {
for (int i = 0; i < sequence_size ; ++i) { // read all the numbers till the end
int number;
// if (std::cin >> number and number > 0 and number <= sequence_size and already_seen[number] == 0 ) already_seen[number] = 1;
std::cin >> number ; // assume there would be no input failure
if (number > 0 and number <= sequence_size and already_seen[number] == 0 ) already_seen[number] = 1 ;
// else {
// cout << "0" << endl;
// loop = false;
// }
else loop = false ;
}
// if (loop) cout << "1" << endl;
std::cout << ( loop ? "1\n" : "0\n" ) ;
}
}
|
> 3. Is it possible to use endl instead of \n in this line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' )
No.
std::endl is an output manipulator; it is a function.
http://www.cplusplus.com/reference/ostream/endl/
The type of the second parameter of
std::cin.ignore() is
int - the argument must be an
int that either holds the value of a character or is EOF.
http://www.cplusplus.com/reference/istream/istream/ignore/
> my programming rules stricly says to use endl instead of \n.
I presume that these 'programming rules' were framed by your teacher. Most career teachers who 'teach' C++ are people who have never done any real-life programming in C++.
CppCoreGuidelines:
Avoid endl
Reason
The endl manipulator is mostly equivalent to '\n' and "\n"; as most commonly used it simply slows down output by doing redundant flush()s. This slowdown can be significant compared to printf-style output.
Example
1 2
|
cout << "Hello, World!" << endl; // two output operations and a flush
cout << "Hello, World!\n"; // one output operation and no flush
|
Note
For cin/cout (and equivalent) interaction, there is no reason to flush; that's done automatically. For writing to a file, there is rarely a need to flush.
Apart from the (occasionally important) issue of performance, the choice between '\n' and endl is almost completely aesthetic.
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rio-endl |