Hello, C + + (11) How do I use a string data type to represent a string of text? Automatically infer the Auto keyword of the data type based on the initial value (c + + 11)

Source: Internet
Author: User
Tags locale mul

3.5.2 String Type

We can represent a single character using a variable of type char, so how do we represent a string that has more than one character? We notice that a string is formed by a string that is linked together. Naturally, the simplest and most straightforward approach is to use arrays, a form of data organization and management, that organizes multiple data elements of the same type into a sequence of data for easy access. For more information, refer to section 3.6 for an introduction to the array) to hold the individual characters in a string, and finally to use a special character, '% ', to represent the end of the string to concatenate character data of multiple char types into a string. For example:

// define a character array to hold the string
char msg [32];
// Save each character in sequence to the corresponding position of the array
msg [0] = ‘G’; // the first character, saved to the first position in the array, and so on
msg [1] = ‘o’;
msg [2] = ‘o’;
msg [3] = ‘d’;
// Save a '\ 0' in the last position, which means the end of the string
msg [4] = ‘\ 0’;
// output the string in msg array
cout << msg << endl;

The way a string is represented by a character array is simple and feasible, but it has many inconveniences to use. In C + +, we are using STL (Standard Template Library), which is a set of function libraries implemented by template technology, which provides some common containers and algorithms for processing data. Here the string type, string, is a type of data that is defined by it to represent a string. As for the STL, we will describe in detail in a later 8th chapter a string of string types that are defined in strings to represent strings. This type of string is essentially a char-type character array wrapper, while saving the string data also adds some common operations on the string, such as getting the length of the string, looking for specific characters, etc., so that the processing of strings is much more convenient. Just as char and wchar_t correspond to each other for different ranges of characters, as with string, C + + provides a wstring string type that can handle wchar_t type characters. For example:

#include <iostream>
#include <string> // The header file where the string type is located

using namespace std;

int main ()
     // Define a string type variable, which represents an English string
     string strEn = "Good Morning!";
     // Define a wstring type variable, which represents a Chinese string
     wstring strChs = L "Shan A-82103";
     // Use cout to output a string of type string
     // Use wcout to output a wstring type string
     cout << strEn;

     wcout.imbue (locale ("chs")); // set the locale

     wcout << strChs << endl;

     return 0;

As you can see, because of the different string and wstring encoding, different strings need to be used in different ways when outputting. For a string variable of type wstring, you need to use the Wcout object when outputting, and you need to set the encoding of the character with the imbue () function. Also, it is worth pointing out that the English string can be represented not only as a string type, but also as a wstring type, while the Chinese string can only be represented using the wstring type.

The string type not only wraps a character array, it can store individual characters in a string, but also provides a number of string-related operations, such as the ability to get a string length, or to find a character in a string, and so on, which greatly facilitates the processing of strings. For example:

// Define a string variable to hold the username entered by the user
string strName = "";

cout << "Please enter your username:" << endl;
// Get the string entered by the user and save it to the strName variable
cin >> strName;
// Get the length of strName through the length () function of string type
// And determine if its length is less than 6 (whether there are less than 6 characters in the string)
if (strName.length () <6)
     // if it is less than error
     cout << "Error: user name contains at least 6 characters" << endl;

In the above code, we first define a string variable strname, which holds the user-entered user name string, and then uses CIN to get the user-entered string and save it to the strname variable. The length of the string, which is the number of characters in the strname, is then used by the string-type long () function. Finally, the IF condition structure is used to compare it with the string length 6 we require, and if the condition is not met, the error is indicated.

Know more: Auto type variable--infer real data type based on initial value

In the previous chapters, we covered a variety of data types in C + +: int types that represent integers, float types that represent floating-point numbers, and char types that represent a single character, as well as string types that represent strings. These data types, which are different in purpose, provide a rich choice for us to define variables to represent real-world data. However, there is a common requirement for these data types to be used, that is, when defining variables to represent data, we must first know what type of data to represent, whether it is a decimal or a string of characters, and then we can determine whether to use float or string accordingly. In development practice, however, it is sometimes not very easy to determine the type of data a variable should have. For example, when assigning a complex expression as an initial value to a newly defined variable, it is often difficult to determine the data type of the expression, so that the data type of the variable should not be determined. To solve this problem, C++11 provides us with the Auto keyword, which is used as the data type defined by a variable, and the compiler automatically infers the variable's reasonable data type based on the initial value of the variable, without the need for us to specify it. For example:

auto x = 7; // initialize the variable x with the integer 7, x is inferred to be of type int
auto y = 1.982; // Initialize variable y with floating point number 1.982, y is inferred to be of type double

Handler GetHandler ();
// Use the return value of the GetHandler () function to initialize the variable handler
// handler is inferred as Handler type
auto handler = GetHandler ();

Here, when we define the variable x, we do not specify its specific data type, instead we use Auto instead. This way, when the compiler compiles this code, it automatically infers that the actual data type of x is int based on the initial value of 7. Similarly, a variable y initialized with a floating-point number of 1.982 is automatically inferred by the compiler as a double type, and the last variable, handler, is initialized to the return value type handler of the GetHandler () function. Although the Auto keyword automatically infers the data type of a variable based on its initial value, its use does not take an additional compilation time. Have the benefit without the extra cost, auto keyword is like the free big gift of the mall, such a big bargain who does not like it?

In fact, you can think of the Auto keyword as a placeholder for the data type in a variable definition, which occupies a location that should be the specific data type. At compile time, the compiler infers the specific data type of the variable based on the initial value of the variable, and then replaces the Auto keyword, and becomes a normal variable definition with a specific data type. Defining a variable with the Auto keyword has no difference in the form of a generic definition variable, except that when you define a variable with the Auto keyword, the variable must have an initial value:

auto variable name = initial value expression; // assignment form
// or
auto variable name {initial value expression}; // initialize list form

Thus, the data type of the result of the initializer evaluation is inferred by the compiler as the data type of the variable.

Usually when defining a variable, if it is difficult to accurately infer its data type, or if the data type of the variable is difficult to write, you can use auto as the variable's data type to define the variable, and the true data type is left to the compiler to infer from the variable's initial value. The computer is much faster than the human brain to do this kind of menial work. This not only eliminates the hassle of inferring data types ourselves, avoids possible human errors, but also achieves the purpose of simplifying the code. For example:

template <typename T>
// The "&" symbol after the data type vector <T> indicates that the variable defined after it is a reference
// References are a special way of accessing data in C ++, which we will introduce in detail later in Section 7.1
void printall (const vector <T> & v)
     // Automatically infer the data type of the variable it based on the return value type of v.begin ()
     for (auto it = v.begin (); it! = v.end (); ++ it)
         cout << * it << endl;

To show the same meaning, if there is no auto keyword to help, we have to write the following tedious form:

template <typename T> void printall(const vector<T>& v)
{ for (typename vector<T>::const_iterator it = v.begin();
        it != v.end(); ++it)
        cout << *it << endl;

In addition to simplifying the code, the Auto keyword can sometimes even help us accomplish some of the tasks that could not be done before the c++11, becoming a necessity. For example, in a template function, when the data type of a variable is dependent on a template parameter, if you do not use the Auto keyword, you will not be able to determine the data type of the variable at all, because we simply cannot predict in advance what data type the user uses as a template parameter to invoke the template function. Thus, the data type of the variable cannot be determined. But after using the Auto keyword, all the puzzles will be solved. For example:

template <typename T, typename U>
void mul (const T & t, const U & u)
     // ...
     // Use the auto keyword as the data type, the compiler will use the actual data types of u and t,
     // Automatically infer the data type of the variable tmp
     auto tmp = t * u;

     // ...

Here, the data type of the variable tmp should be the same as the data type that the template parameter T and u multiply result in, that is, the data type that depends on T and U. For programmers, when writing this template function, the type of the template parameter T and U is not yet determined, so the type of the variable TMP cannot be determined. So, we use the Auto keyword as a placeholder to occupy the location of the data type, and the true data type is left to the compiler at the time of final compilation, based on the type of template parameters T and u given. In this way, it is possible to turn a thing that is impossible.

Using the Auto keyword, you can automatically infer its data type based on the initial value of the variable, which greatly facilitates the definition of complex data type variables. However, this is good, but there is a drawback, that is, each inferred data type can only be used once when defining variables, can not be preserved to continue to use. It's not easy to infer that the data type can only be used once, which is a little less carbon-friendly. And sometimes, we need the inferred data to be preserved so that it can be reused to define multiple variables of the same type. To compensate for this shortcoming, C++11 also provides a decltype keyword. It uses the following syntax form:

typedef decltype (expression) user data type;

where decltype (expression) is the inferred data type of the expression (declared type), which is the data type of the expression that evaluates the result. The TypeDef, however, defines the data type as a user-defined data type, in other words, a name for the inferred data type, which can be used as a new data type, where any data type needs to be defined, such as defining variables, creating objects, and so on. For example, we can rewrite the above example with the Decltype keyword:

template <typename T, typename U>
void mul (const T & t, const U & u)
     // ...
     // Use decltype to get the data type of t * u,
     // and use the typedef keyword to define it as a new data type M
     typedef decltype (t * u) M;
     // Use this new data type M to define pointer variables (variables that represent variables or function addresses) and create M type objects
     M * tmp = nullptr;
     tmp = new M; // ...

Auto and Decltype have similar functions, and can infer the specific data type of an expression. However, the use of the two is slightly different. Auto is the best candidate if we just want to determine the appropriate data type for a variable based on the initial value. It is only when we need to infer the data type of an expression and reuse it as a new data type (for example, to define multiple identical types of variables) or to use it alone (for example, as a function's return value type), we really need to use decltype.

[CHEN1] Confirm

Hello, C + + (11) How do I use a string data type to represent a string of text? Automatically infer the Auto keyword of the data type based on the initial value (c + + 11)

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.