1. istringstream字符串流
#include
<iostream>
#include
<sstream>
#include
<string>
using
namespace
std;
struct
MyStruct
{
string
str1,
str2,
str3;
double
db;
int
num;
char
ch;
};
void
main()
{
string
mystring("china
google microsoft 12.9 123 A");
MyStruct
struct1;
istringstream
input(mystring);//创建一个字符串扫描流
input >>
struct1.str1
>> struct1.str2
>> struct1.str3
>> struct1.db
>> struct1.num
>> struct1.ch;
cout <<
struct1.str1
<< endl;
cout <<
struct1.str2
<< endl;
cout <<
struct1.str3
<< endl;
cout <<
struct1.db
<< endl;
cout <<
struct1.num
<< endl;
cout <<
struct1.ch
<< endl;
cin.get();
}
2.实现类似字符串截取的功能
#include
<iostream>
#include
<sstream>
#include
<string>
using
namespace
std;
//实现类似字符串截取的功能
void
main()
{
char
mystring[50] =
"china#123#A";
for (char
*p =
mystring; *p
!= ‘\0‘;
p++)
{
if (*p
== ‘#‘)
{
*p =
‘ ‘;
}
}
istringstream
input(mystring);//创建一个字符串扫描流
string
str;
int
num;
char
ch;
input >>
str >>
num >>
ch;
cout <<
str <<
endl;
cout <<
num <<
endl;
cout <<
ch <<
endl;
cin.get();
}
运行结果:
3.实现类似字符串截取的功能
#include
<iostream>
#include
<sstream>
#include
<string>
using
namespace
std;
//实现类似字符串截取的功能
void
main()
{
ostringstream
MYOUT;
char
str[100] = { 0 };
//ostringstream MYOUT(str,sizeof(str));
char
str1[50] =
"a1234567b";
MYOUT <<
"a1234b" <<
" " << 123<<
""<< 234.89 <<
" " <<
‘h‘ <<
" " <<
str1 <<
endl;
cout <<
MYOUT.str();
//cout <<str;
cin.get();
}
运行结果如下:
4.字符串流中的put
#define
_CRT_SECURE_NO_WARNINGS
#include
<iostream>
#include
<sstream>
#include
<string>
#include
<stdlib.h>
using
namespace
std;
void
main()
{
stringstream
mystr;//字符串进行输入
mystr.put(‘X‘).put(‘Y‘);//连个字符输入
mystr <<
"ZXCV";//字符串输入
cout <<
mystr.str();
string
str =
mystr.str();//定义字符串接受值
char
ch;
//从字符串内部读取一个字符
mystr >>
ch;
cout <<
"\n";
cout.put(ch);
cout <<
"\n";
cout <<
mystr.str();
std::cin.get();
system("pause");
}
运行结果
5.str()将流转换成为字符串string
#define
_CRT_SECURE_NO_WARNINGS
#include
<iostream>
#include
<sstream>
#include
<string>
#include
<stdlib.h>
using
namespace
std;
void
main()
{
stringstream
mystr;//sprintf功能
char
cmd1[30] = { 0 };
char
cmd2[30] = { 0 };
cin.getline(cmd1,
30).getline(cmd2,
30);//输入两个字符串
mystr <<
cmd1 <<
"&" <<
cmd2;//字符打印
string
str =
mystr.str();//定义字符串接受值
system(str.c_str());
char
cstr[50] = { 0 };//默认的字符串
strcpy(cstr,
str.c_str());
cout <<
cstr <<
endl;
for (char
*p =
cstr; *p
!= ‘\0‘;
p++)
{
if (*p
== ‘&‘)
{
*p =
‘ ‘;
}
}
char
newcmd1[30] = { 0 };
char
newcmd2[30] = { 0 };
stringstream
newstr(cstr);//sscanf的功能
newstr >>
newcmd1 >>
newcmd2;
cout <<
newcmd1 <<
"\n" <<
newcmd2 <<
endl;
system("pause");
}