the stringstream usage introduced

本文详细介绍了C++标准库sstream如何简化类型转换,并提供了一种安全且自动化的读取方式,避免了传统的stdio.h风格转换可能导致的缓冲区溢出和不可预测后果。通过使用sstream,可以自动推断类型并存储内部缓冲区,减少内存管理的复杂性。同时,文章还展示了如何重用sstream对象进行多次转换,以及如何使用模板类型转换来实现任意类型的转换。

原文链接:http://www.phonesdevelopers.com/1791266/

The stringstream main has two functions: to simplify the type conversion and one-time read data:

Stringstream object to simplify the type conversion 
The C + + standard library <sstream> the than ANSI C <stdio.h> more advanced features, simple, type-safe, and scalability. In this article, I'll show you how to use these libraries to implement security and automatic type conversion.

Why learn

If you have been accustomed to conversion of <stdio.h> style, perhaps the first thing you will ask: Why did it take the extra effort to learn based convert <sstream> type? Perhaps a simple example below review can convince you. Suppose you want to sprintf () function to a variable of type int is converted to a string type. In order to accomplish this task, you must make sure that the card destination buffer large enough space to accommodate the converted string. In addition, you must also use the correct formatting character. If you are using the incorrect formatting characters will result in a non-predictable consequences. Here is an example:

int n = 10000;

chars [10];

sprintf (s, "% d", n) ;/ / s in "10000" 

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

int n = 10000;

char s [10];

sprintf (s, "% f", n) ;/ / see! Error formatting characters 

In this case, the programmer mistakenly use% f format character instead of% d. Therefore, s calling sprintf () contains an undefined string. If able to automatically infer the correct type, it is not better?

Into the stringstream 

N and s the type identified at compile time, the compiler has enough information to determine which transitions are needed. on the use of the standard classes declared in the <sstream> library that automatically selects the necessary conversion. Moreover, the conversion result is stored in the the stringstream object of internal buffer. You do not have to worry about buffer overflows, because these objects are allocated automatically as needed storage space. 

Your compiler supports <sstream>? 

<sstream> library has only recently been included in the C + + standard. (Do not be deleted before the release of the <sstream> standard <strstream> confused.) Therefore, the old compiler, such as gcc2.95does not support it. If you happen to use this compiler and want to use <sstream>, it is necessary to first upgrade the update. 

<sstream> library defines three types: istringstream, ostringstream and stringstream, were used for the flow of input, output, and input and output operations. In addition, each class has a corresponding wide character set version. Simplicity, I mainly stringstream center, because each conversion to be related to the input and output operations. 

Note <sstream> use the string object instead of an array of characters. This avoids the risk of buffer overflow. Moreover, the incoming parameters and the target object type is automatically derived, even with incorrect formatting character there is no danger. 

string to int conversion 

string result = "10000"; 
int n = 0; 
stream << result; 
stream >> n; / / n is equal to 10000 

Stringstream object reuse

If you intend to use the same stringstream object in the multiple conversions Remember then clear () method before each conversion;

Reuse the same in the multiple conversions stringstream (rather than each time to create a new object) object is efficiency. stringstream object's constructor and destructor are usually very CPU time-consuming.

Using a template type conversion

You can easily define the function template to an arbitrary type to a specific type of target. For example, there is a need for a variety of digital values, such as int, long, double, etc. convert string to_string () function to a string type and an arbitrary value t is the parameter you want to use. to_string () function tconverted to a string and writes the result. Str () member function to get the stream's internal buffer a copy:

template <class T>

void to_string (string & result, const T & t)

{

ostringstream oss ;/ / create a stream

oss << t ;/ / value is passed as stream

result = oss.str () ;/ / Get transfer of characters converted and written to the result 
} 

In this way, you can easily convert a variety of value to a string: 

the to_string (s1, 10.5) ;/ / double to string

the to_string (s2, 123) ;/ / int to string

to_string (s3, true) ;/ / bool to string 

The conversion can further define a generic template is used to convert between any type. The function template convert () containing two template parameters out_type the in_value function is convert in_value value into out_type type: 

template <class out_type,class in_value>

out_type convert (const in_value & t)

{

stringstream stream;

stream << t ;/ / to the stream by value

out_type result ;/ / store the converted results

stream >> result ;/ / write to result value

return result;

}

Convert ():

double d;

string salary;

string s = "12.56";

D = the convert <double> (s) ;/ / d is equal to 12.56

salary = convert <string> (9000.0) ;/ / salary equal to "9000" 

Conclusion

 

In the past to stay program code and pure C program, the traditional <stdio.h> form conversion with us for a long period of time. However, as described in the text, based on stringstream conversion has a type-safe and will not overflow so eye-catching features, so that we have sufficient reason to abandon <stdio.h> <sstream>. <sstream> library also provides another feature - scalability. You can overload to support conversion between the custom type. 

Some examples: 

The stringstream usually used for data conversion.

Compared to the conversion of the c library, it is more secure, automatic and direct.

 

Example 1: 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; / / int input stream 
stream >> result; / / int value extracted from the stream in front of the inserted 
std :: cout << result << std :: endl; / / print the string "1000" 
}


Example 2: In addition to the basic types of conversion, also supports char * conversion

# Include <sstream> 
# Include <iostream> 

int main () 
{ 
std :: stringstream stream; 
char result [8]; 
stream <<   8888; / / insert to the stream 8888 
stream >> result; / / extract stream value to the result 
std :: cout << result << std :: endl; / / screen displays "8888" 
}


Example: when multiple conversions, you must call the stringstream member function clear ()

# Include <sstream> 
# Include <iostream> 
int main () 
{ 
std :: stringstream stream; 
int first, second; 
stream <<     "456"; / / insert the string 
stream >> first; / / convert int 
std :: cout << first << std :: endl; / / print 456 
stream. clear (); / / during multiple conversions must be cleared before the stream 
stream <<     true; / / insert bool value 
stream >> second; / / extract int 
std :: cout << second << std :: endl; / / print 1 
}


Disposable all the documents read into the memory of one of the methods:

Many times larger amount of file IO always become a bottleneck, in order to improve efficiency, and sometimes you want large chunks of the file is first read into the re-processing. The following analysis of the two usual handling.

File a one-time read into the string.

Looks like std :: getline, istream :: getline or operator << operator >>, etc. do not provide a mechanism to read the end of the file, only istreambuf_iterator can be done:

{

ifstream in ("input.txt"); 
string instr ing ((istreambuf_iterator <char> (in)), istreambuf_iterator <char> ());

}


in front of the string constructor parameters to add a layer in order to avoid compiler mistaken function declaration == ...

This read into the string with the dynamic growth, lack of space will trigger additional realloc and copy operations, it is necessary to improve the efficiency of pre-allocate enough space:

{

ifstream in ("input.txt"); 

in seekg (0, ios :: end); 
streampos len = in. tellg (); 
in. seekg (0, ios :: beg); 

string inString; 
instring. reserve (len); 
instring. assign (istreambuf_iterator <char> (in), istreambuf_iterator <char> ());

}


File a one-time read .

filebuf and stringbuf not directly by rdbuf () redirected from filebuf to stringbuf need a copy operation. The easiest way is to copy the entire streambuf:

{

ifstream in ("input.txt"); 
stringstream ss; 
ss << in rdbuf ();

}


The string is the same, there is also a space realloc and copy. Streambuf buffer is not so easy to operate, the solution is to give him manually specify a space:

{

ifstream in ("input.txt"); 
in seekg (0, ios :: end); 
streampos len = in. tellg (); 
in. seekg (0, ios :: beg); 
the vector <char> buffer (len); 
In the read (& buffer [0], len); 

stringstream ss; 
the SS rdbuf () -> pubsetbuf (& buffer [0], len);

}


For example:

The file test content:

A 0.1 
B 1 
C 0.33


One-time read the file:


# Include <iostream>

# Include <fstream>

# Include <string>

# Include <sstream> 

int main ()

{

ifstream in ("test");

   

in.seekg (0, ios :: end); 
streampos len = in.tellg (); 
the vector <char> buffer (len); 
in.seekg (0, ios :: beg); 
in.read (& buffer [0], len);

   

stringstream ss;

ss.rdbuf () -> pubsetbuf (& buffer [0], len);

string name; 
double rate;

while (ss >> name && ss >> rate) 
{ 
cout << name << "/ t" << rate << std :: endl; 
} 
return 0; 
} 

The output is:

A 0.1 
B 1 
C 0.33


内容概要:本文系统阐述了Java Persistence API(JPA)的核心概念、技术架构、核心组件及实践应用,重点介绍了JPA作为Java官方定义的对象关系映射(ORM)规范,如何通过实体类、EntityManager、JPQL和persistence.xml配置文件实现Java对象与数据库表之间的映射与操作。文章详细说明了JPA解决的传统JDBC开发痛点,如代码冗余、对象映射繁琐、跨数据库兼容性差等问题,并解析了JPA与Hibernate、EclipseLink等实现框架的关系。同时提供了基于Hibernate和MySQL的完整实践案例,涵盖Maven依赖配置、实体类定义、CRUD操作实现等关键步骤,并列举了常用JPA注解及其用途。最后总结了JPA的标准化优势、开发效率提升能力及在Spring生态中的延伸应用。 适合人群:具备一定Java基础,熟悉基本数据库操作,工作1-3年的后端开发人员或正在学习ORM技术的中级开发者。 使用场景及目标:①理解JPA作为ORM规范的核心原理与组件协作机制;②掌握基于JPA+Hibernate进行数据库操作的开发流程;③为技术选型、团队培训或向Spring Data JPA过渡提供理论与实践基础。 阅读建议:此资源以理论结合实践的方式讲解JPA,建议读者在学习过程中同步搭建环境,动手实现文中示例代码,重点关注EntityManager的使用、JPQL语法特点以及注解配置规则,从而深入理解JPA的设计思想与工程价值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值