The method of realizing Raw_input in C + + _c language

Source: Internet
Author: User

This article describes the implementation of C + + Raw_input method, share for everyone to reference. The specific methods are analyzed as follows:

Accustomed to Python, now write C + + code feel a little less smooth. Today to illustrate the example of C + + implementation of the Raw_input method.

Friends with Python know that there is a raw_input in Python that can be used as follows:

Print raw_input ("Input a number:")

It is convenient to use a function that has both input hints and return values. But now the problem is in C + +, I also want to do so, how to do? In fact, writing a function can also be easily implemented, such as:

int raw_input (const char* Tips)
{
    cout<<tips;
    int A;
    cin>>a;
    return A;
}

This is the implementation of integer data input function: First through the cout output hint content, such as "Input number:" And so on, and then define an integer variable A, and through CIN to obtain the value of the data, and finally return the integer data. Can be called as follows:

Cout<<raw_input ("Input number:") <<endl;

Functionality is implemented, and if you change the type to string, it's the same as Python. But I still think this is not flexible: I have to write every type, I feel very uncomfortable, I want a more flexible than the Python function. Standard library No, just write it yourself.

This is implemented with the help of C + + templates, as shown in the following example:

Template <class t1,class t2>
T1 raw_input2 (T2 tips)
{
    T1 A;
    cout<<tips;
    cin>>a;
    return A;
}

This, like the principle above, is not explained here. The call is as follows:

Cout<<raw_input2<string,string> ("Input string:") <<endl;

It's much more convenient.

I hope this article will help you with the C + + program design.

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.