今天做了一道字符串转化大小写的题,做完之后突然想看一下别人是怎么写的,于是就发现了标题所述的一种用C++流的一种方法:感觉很方便,但是自己虽然学完C++这门课,竟然一(wu)点(li)也(to)不(cao)知(!)道,实在惭愧!!,看了是有必要好好回头在复习研究一番!
以下翻译自:click here
1stringstream对象的使用
#include<sstream>
#include<iostream>
using namespace std;
int main()
{
string line,word;
while(getline(cin,line))
{
stringstream stream(line);
cout<<stream.str()<<endl;
while(stream>>word){cout<<word<<endl;}
}
return 0;
}
关于
getline
以及相关输入的用法详情可以参考翻译的另一篇:
javascript:void(0)
输入:shanghai no1 school 1989
输出:shanghi no1 school 1989
shanghai
no1
school
1989
2stringstream提供的转换和格式化
#include<sstream>
#include<iostream>
using namespace std;
int main()
{
int val1 = 512,val2 =1024;
stringstream ss;
ss<<"val1: "<<val1<<endl //“val1: "此处有空格,字符串流是通过空格判断一个字符串的结束
<<"val2: "<<val2<<endl;
cout<<ss.str();
string dump;
int a,b;
ss>>dump>>a
>>dump>>b;
cout<<a<<" "<<b<<endl;
return 0;
}
输出为:val1: 512
val2: 1024
512 1024
第一处黑体字部分:将int类型读入ss,变为string类型
第二处黑体字部分:提取512,1024保存为int类型。当然,如果a,b声明为string类型,那么这两个字面值常量相应保存为string类型
3其他注意
#include <cstdlib>
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
stringstream ss;
string s;
ss<<"shanghai no1 school";
ss>>s;
cout<<"size of stream = "<<ss.str().length()<<endl;
cout<<"s: "<<s<<endl;
ss.str("");
cout<<"size of stream = "<<ss.str().length()<<endl;
}
输出:
size of stream = 19
s: shanghai
size of stream = 0
,
练习题 HDU 2564
代码;'
//一般写法
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
char str[1001];
int main()
{
int n;
int i;
cin>>n //输入测试次数;
getchar();
while(n--)
{
gets(str); //输入词组;
for(i=0; i<strlen(str); i++) //将词组中的小写字母都转为大写字母
if(str[i]>='a'&&str[i]<='z')
str[i]-=32;
for(i=0; i<strlen(str); i++)
{
if(i==0&&str[i]!=' ')
printf("%c",str[0]);
else if(str[i]!=' '&&str[i-1]==' ')//判断是否是一个词组的开头字母;
printf("%c",str[i]);
}
printf("\n");
}
return 0;
}
// stringstream对象
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <sstream>
using namespace std;
char str[1001];
int main()
{
int n;
cin>>n;
getchar();
while(n--)
{
cin.getline(str,1000);
stringstream str(str);
char a[20];
while(str>>a)cout<<(char)toupper(a[0]); //toupper 函数 :将小写字母转化为大写字母,tolower函数—:将大写字母转换为小写字母
cout<<endl;
}
return 0;
}