A question that makes errors common to advanced C ++ programmers

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.