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.