Conversion of strings to other basic types--from C to c++11

Source: Internet
Author: User
Tags sprintf

Transferred from IBM compiler China development team "String-atoi/itoa in C++11"

In C++11, due to the introduction of rvalue reference, the performance of std::string has been greatly improved. On the other hand, we can also see that the new language adds a lot of new APIs to the Std::string class. The interesting thing is the std::string member function Stoi series, and the Std::to_string global function. Although these two APIs are very humble, they add a practical means for C++11 formatted output (formatted I/O). We can have a meeting in a minute. C,c++98,c++11 how we deal with ATOI/ITOA issues:

In the C era, we usually encounter the problem of atoi (string-to-numeric conversion) When we use the Atoi function:

int num = atoi (CSTR);

The CStr here is usually a char or const char type String. The result returned by the function is a decimal integer represented by the string. The whole effect of the function is equivalent to another function in Strtol:

int num = strtol (CStr, NULL, 10);

Compared to Atoi,strtol, the last parameter, "Radix", indicates that the function takes a few decimal values (the number can be from 2 to 34, the reason for this range is obvious). Removing strtol will set global errno in case of an error, and its effect is almost identical to Atol in the Atoi series.

When the C-era solves itoa (numeric to string conversion), the sprintf function is used:

Int Myint;
Char Buf[size];
sprintf (buf, "My data is%d", Myint);

The output control of the character here is given a special character such as "%d". With special characters and mates with variable-length parameters (sprintf is a variable-length parametric function), we get the expected output of formatted I/O.
Here we can see the characteristics of C in the treatment of Atoi/itoa, the basic can be summarized as follows:

    1. Atoi does not check for errors in strings. This means that the programmer who uses the API will have to check for errors, or must determine that the errors are not always present in the actual use or can be tolerated by the program.
    2. The alternative version of Atoi Strtol checks the string for errors, but uses the standard way in POSIX, setting errno. This means that programmers using strtol need to detect the global variable errno after calling Strtol if they want to detect errors in the string.
    3. sprintf not responsible for memory management. Typically, programmers are cautioned to replace sprintf with snprintf or other versions with memory boundary checks. This reduces the likelihood of a buffer overflow occurring. But in general this is just a defensive approach in programming, and from the programmer's point of view, memory management is still a problem.
    4. sprintf, like printf, does not check the parameter type (because it is implemented in a variable-length function), so if the argument does not match escape character, it will not be found at runtime until the mismatched output is discovered. However, this error is the easiest to fix relative to the other three points.
      So the solution to the Atoi/itoa problem in C is not to make the programmer happy. In the case of bad input, the programmer must handle all kinds of exceptions carefully to prevent the program from going astray. But in turn, the Atoi/itoa in C is very intuitive and easy to understand, so even in C + + This code is not uncommon.

In the c++98 era, Atoi/itoa can be done using the new C + + standard library. Specifically, a stream template class that uses C + +. It is worth noting that in the c++98 code, although the storage of strings is perfectly possible, using the std::string type in C + + code, memory can be managed efficiently, and member functions can throw exceptions, so it is more appropriate for C + + code. The type of flow template for the std::string type is std::stringstream. With the global overloaded operator«and Operator»,std::stringstream, it is easy to accomplish atoi or itoa tasks, such as:

Ostringstream OSS;
Oss«15«"is int," «3.14f«"is float." «endl;
Cout«oss.str ();

The OSS is a string stream object that can be used for itoa work. and

Istringstream ISS ("14.1f");
int A;
float B;
Iss»a»b;
Cout«a«"" «B«ENDL;

The ISS string stream object in the code above can be used as a atoi.
in design, Std::stringstream is a good design. This is due to the fact that the code using Std::stringstream looks very intuitive. And because it comes from the C + + library, programmers are often less concerned about whether there will be exception thrown-because if the code is not Try-catch block, the exception will directly terminate (call Std::terminate) if it is thrown. This approach to error resolution is more straightforward for programmers, because the program terminates at the point where it is easy to find the problematic code location. and the C-era Atoi/itoa, as we talked about, requires programmers to focus on exceptions, and if you miss out on handling exceptions (which is common), the program may run with diabetes. Of course, because StringStream is always "attached" to a string object that can be managed by itself, programmers often don't have to worry about any memory allocation issues.
from a design point of view, Std::stringstream is almost impeccable. But in actual use, as we mentioned above, many people still prefer to use the C processing method to complete the Atoi/itoa. There are probably two reasons for this:

    1. The Std::stringstream is conceptually indirect. This indirection comes from the association between Std::stringstream and Std::string. Typically, a Std::stringstream object is always associated with its "attached" std::string object. Either it is constructed from a string object (ISS ("14.1f") in the previous example), or it must be converted to a String object (Oss.str () in the example above). And the novice will often intuitively write string a«12«"is int", such an error code.
    2. The inconvenience of formatting the output. Compared to Sprintf,std::stringstream is a stream object, which means that it also has a higher learning cost. Simple sprintf, just look through the escape character manual, you can beautifully format the output. If you use a stream for formatted output, you need to control a state machine. Many times, programmers need to be concerned about the impact of the previous state on the existing output. It also often means that more code needs to be entered. A lot of times programmers feel very troublesome. So even though sprintf has missing type matching, exception handling, memory management, and so on in C + + code, programmers are still using it without hesitation. (In this regard, Boost::format may give a cross-platform intermediate solution)
      From the above two aspects, the use of Std::stringstream to complete the Atoi/itoa although is more C + + style, full-featured way, but due to the increase in learning costs and format output of the inconvenience, its application in the actual scene is greatly limited.

In c++11, the standard Committee may have noticed that this "simpler than complete" is more important, so in c++11, the standard adds functions such as global function std::to_string, Std::stoi/stol/stoll, and so on. (the original paper called Simple numeric access,n1982) is very easy to use:

string S;
s + = to_string (+) + "is int,";
s + = to_string (3.14f) + "is float.";
Cout«s«endl;

The to_string here will be converted according to the type of the parameter. and

String S ("12");
int i = Stoi (s);
Cout«i«endl;

This code can successfully complete the atoi task. Because it is a function introduced by c++11, it has all the C + + library code features that are not available in a: type-based processing, throwing exceptions, and automatic memory management.

As you can see, std::to_string may involve some string links in the actual use. As we mentioned at the beginning of the article, string links in c++98 have been an important aspect of the C + + language being criticized for performance below C. This is greatly mitigated by the introduction of rvalue references in c++11. Therefore, the practicability of such a function is greatly enhanced at this std::to_string. But Std::to_string is not the ultimate way of itoa. In the case of floating-point numbers, to_string even the basic control functions such as floating-point digital display control are not available, so its greatest feature is to highlight its ease of use. C + + programmers do not have to define a Std::stringstream object to do itoa work that is safe and effective and does not care about any memory.
and Std::stoi/stol/stoll ... The series is simple enough to complete only one numeric conversion, which is far worse than the operator» that always returns Std::stringstream &. The latter can convert multiple values in a single line of code. But the former's greatest feature is still prominent in ease of use, without having to "attach" a std::stringstream type. This is sufficient for many programs that do not require complex atoi.

Conversion of strings to other basic types--from C to 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.