I have seen it in a forum before. It has been too long and I don't quite remember it. Today I turned it out and found it quite classic. I posted it. As follows:
This is a typical problem that many people may encounter. This is also a problem that is frequently encountered in C ++ input.
The C ++ code is as follows:
#include <iostream> 3.int main() 4.{ 5. using namespace std; 6. const int ArSize = 20; 7. char name[ArSize]; 8. char dessert[ArSize]; 9. 10. cout << "Enter your name:\n"; 11. cin >> name; 12. cout << "Enter your favorite dessert:\n"; 13. cin >> dessert; 14. cout << "I have some delicious " << dessert; 15. cout << " for you, " << name << ".\n"; 16. return 0; 17.}
You can ignore the answer and think about the running result of this program. If you are correct, it means that your c ++ learning is still better ....
The answer is as follows:
Let's take a look at the differences between the following code and the above Code:
1.// instr2.cpp -- reading more than one word with getline 2.#include <iostream> 3.int main() 4.{ 5. using namespace std; 6. const int ArSize = 20; 7. char name[ArSize]; 8. char dessert[ArSize]; 9. 10. cout << "Enter your name:\n"; 11. cin.getline(name, ArSize); // reads through newline 12. cout << "Enter your favorite dessert:\n"; 13. cin.getline(dessert, ArSize); 14. cout << "I have some delicious " << dessert; 15. cout << " for you, " << name << ".\n"; 16. return 0; 17.}
If you see the problem, the key is this cin. It does not determine the length of the Cross-border. This is similar to scanf. Therefore, you must specify the length of the input when entering the data, to prevent cross-border attacks.