C + + StringStream simple usage

Source: Internet
Author: User

From: http://blog.csdn.net/zaishaoyi/article/details/46682033

StringStream

StringStream is another string-stream object provided by C + +, which is similar to the iostream and fstream that have been learned before. To use StringStream, you must first join this line:

#include <sstream>

StringStream is mainly used to split a string, you can first use clear () and STR () to set the specified string as a starting content, and then use >> to output a separate data, for example:

string S;
StringStream SS;
int A, B, C;
Getline (CIN, s);
Ss.clear ();
SS.STR (s);
SS >> a >> b >> c;

Here we see an example of using StringStream:

Topic: The first line of input has a number n represents the next n rows of data, each row contains an integer that is not fixed (up to 20, with a maximum of 200 characters per line), please write a program that prints the sum of each line.

Input:

3
1 2 3
20 17 23 54 77 60
111 222 333 444 555 666 777 888 999

Output:

6
251
4995

The program is as follows:

string S;
StringStream SS;
int n, I, sum, A;
CIN >> N;
Getline (CIN, s); Read the line for
(i=0 i<n; i++)
{
    getline (CIN, s);
    Ss.clear ();
    SS.STR (s);
    sum=0;
    while (1)
    {
        ss >> A;
        if (Ss.fail ()) break;
        sum+=a;
    }
    cout << sum << endl;
}

The string type is a more convenient implementation of the char * type in the C language. Using this type, you don't have to think about the memory thing anymore. The convenience of the string object, while doing rapid development, is quite excellent. However, here's a reminder that string types are likely to be a source of engineering efficiency problems, and in product-level applications, you should try to avoid using string types in deep loop nesting.
In addition to size (), the most common method for two strings is find and substr. In the following code:

  String str = "AAAADDDDSSDFSASDF";
    size_t pos = str.find ("SSDF", 3);                       Use if (pos = string::npos) to determine if a substring is found.
    string str2 = Str.substr (pos, 5);
The Find function starts with the 3rd position of STR, finds the SSDF substring, and returns the substring's position. The SUBSTR function starts at the POS position, intercepts 5 characters, and assigns values to STR2. In other words, the content after str2 will be Ssdfs.

StringStream is a string stream, often used by me for data segmentation or type conversion. A function that I often use is as follows:
string i2s (int i, int len = 0)
{
    StringStream ss;
    SS << SETW (len) << Setfill (' 0 ') << i;
    Return Ss.str ():
}

This function is called in I2S (7, 3), and the result returned is a string of 007. I usually do this in a loop, which produces or traverses some files.

simplifying type conversions with StringStream objects

The <sstream> in the C + + standard library provides a higher level of functionality than ANSI C <stdio.h>, i.e., simplicity, type safety, and scalability. In this article, I'll show you how to use these libraries to implement secure and automatic type conversions.

Why to learn

If you're used to the <stdio.h> style transformation, you may first ask why you need to devote extra effort to learning the type conversion based on <sstream>. Perhaps a review of the following simple example will convince you. Suppose you want to use the sprintf () function to convert a variable from an int type to a string type. In order to complete this task correctly, you must ensure that the target buffer has enough space to accommodate the converted string. In addition, you must use the correct formatting characters. If you use an incorrect formatting character, it can cause unpredictable consequences. Here is an example:

int n=10000;

CHARS[10];

sprintf (S, "%d", n);//s content is "10000"

So far it looks good. However, a minor change to the code above will crash the program:

int n=10000;

Char s[10];

sprintf (S, "%f", n);/See. Bad formatting characters

In this case, the programmer mistakenly used the%f formatter instead of%d. Therefore, S contains an indeterminate string after the call to sprintf (). It would be better if you could automatically deduce the correct type.

Enter StringStream
Since the type of N and S is determined at compile time, the compiler has enough information to determine which transformations are needed. The standard classes declared in the library take advantage of this and automatically select the required transformations. Also, the result of the transformation is saved in the internal buffer of the StringStream object. You don't have to worry about buffer overflows because these objects automatically allocate storage space as needed

do you have compiler support?

Libraries are only recently included in the C + + standard. (Do not confuse with the standard release before being deleted.) Therefore, the older compiler, such as GCC2.95, does not support it. If you happen to be using such a compiler and want to use it, you need to update it first.

The library defines three kinds: Istringstream, Ostringstream, and StringStream, which are used for flow input, output, and input/output operations. In addition, each class has a corresponding wide version of the character set. For simplicity, I mainly focus on stringstream, because each transformation involves both input and output operations.

Note that you use a string object instead of a character array. This avoids the risk of a buffer overflow. Also, the types of incoming and target objects are automatically deduced, and there is no danger even if an incorrect format character is used.

conversion of string to int

String result= "10000";
int n=0;
stream<<result;
stream>>n;//n equals 10000.

Reusing StringStream Objects

If you intend to use the same StringStream object in multiple conversions, remember to use the clear () method before each conversion;

Reusing the same stringstream in multiple conversions (instead of creating a new object each time) the biggest benefit is efficiency. The construction and destructors of StringStream objects are often CPU-intensive.

Some examples:

StringStream is usually used for data conversion.

Compared to C-Library conversion, it is more secure, automatic and direct.

Example one: Basic data type Conversion example int turn string

#include <string>
#include <sstream>
#include <iostream> 

int main ()
{
    std:: StringStream stream;
    std::string result;
    int i = 1000;
    Stream << i; Extracts the int input stream stream >> result//
    from the stream with the previously inserted int value
    std::cout << result << std::endl;//Print The string "1000"

Example two: the conversion of char * is also supported in addition to the conversion of basic types.

#include <sstream>
#include <iostream> 

int main ()
{
    std::stringstream stream;
    Char result[8];
    Stream << 8888; Inserts 8888 stream >> result into the stream,
    //extracts the value from the stream to result
    std::cout << result << Std::endl; Screen display "8888"

Example three: The StringStream member function clear () must be called when the conversion is repeated more than once.

#include <sstream>
#include <iostream>
int main ()
{
    std::stringstream stream;
    int, second;
    stream<< "456"; Insert string
    stream >> I//convert to int
    std::cout <<-i << Std::endl;
    Stream.clear (); You must clear the stream stream << true before making multiple conversions;//
    insert bool
    stream >> Second;//extract int
    Std::cout < < second << Std::endl;

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.