#include<iostream>
#include<cstdio>
#include<string>
#include<sstream>
using namespace std;
//实验三模板
template <class out_t,class in_t>
out_t convert(const in_t &val ){
stringstream stream;
stream<<val;
out_t res;
stream>>res;
return res;
}
int main(){
freopen("stringstream.txt","r",stdin);
//试验一 区分getline() cin.get()
cout<<"实验一"<<endl;
char ch;
char str[20];
// cin.get(ch);
// ch=cin.get();
//用于读入一个字符
cin.get(str,10);
//往str中读入9个字符 和一个'\0'
cout<<"cin.get= "<<str<<endl;
//不能用string,可以先用char数组然后通过各种方法转换成string
cin.getline(str,10);
//读入一个字符串包括空格
cout<<"cin.getline= "<<str<<endl;
//不能用string,可以先用char数组然后通过各种方法转换成string
getchar();
getchar();
string st;
getline(cin,st);
//只能从行头开始读起,且不会留下行尾回车符等
cout<<"getline= "<<st<<endl;
// 读入一个字符串,包括空格,需挂头文件<string>,参数不能是char数组
gets(str);
cout<<"gets= "<<str<<endl;
//与getline()基本相同
//cin.getline(),gets()可以用在多多维数组里面
getchar();
//常用于读入一个整型后读入字符时,把回车读掉
//实验二 多行读入
cout<<"实验二:"<<endl;
string total="";
while(getline(cin,st)){
total+=st;
}
istringstream csin(total);
cout<<"整个文本文件的字符串如下:"<<total<<"$"<<endl;
string tt;
while(csin>>tt)
cout<<tt<<endl;
//实验三 stringstream通过做类型转换
cout<<"实验三:"<<endl;
float price=12.588;
st=convert<string>(price);
cout<<"$"+st<<endl;//证明一下它是个string
//不能实现string 和C风格字符串的转换
//实验四 C风格字符串 与 string 之间的相互转换问题
cout<<"实验四"<<endl;
cout<<"char* 或 char[] 转string"<<endl;
char *csty="dsafdsafds";
string strsty=csty;
cout<<csty<<endl;
char cty[]="asdfghj";
strsty=csty;
cout<<strsty<<endl;
cout<<"string 转 C-style字符串"<<endl;
string affair;
affair="I am having lunch.";
const char *aff;
//这个必须是const
aff=affair.c_str();
cout<<affair.c_str()<<endl;
const char *p=affair.data();
//必须是const
affair="He is sleeping.";
char q[40];
affair.copy(q,affair.length(),0);
//(存储的变量,复制字符个数,复制的位置)
//这个可以不是const,比较灵活
*(q+affair.length())='\0';
//加上结束符
cout<<q;
return 0;
}
stringstream.txt :
abcdefghijklmnopqr
stuvwxyz
This header defines macros to access the individual arguments of a list of unnamed arguments whose number and types are not known to the called function.
A function may accept a varying number of additional arguments without corresponding parameter declarations by including a comma and three dots (,...) after its regular named parameters:
return_type function_name ( parameter_declarations , ... );
To access these additional arguments the macros va_start, va_arg and va_end, declared in this header, can be used:
First, va_start initializes the list of variable arguments as a va_list.
Subsequent executions of va_arg yield the values of the additional arguments in the same order as passed to the function.
Finally, va_end shall be executed before the function returns.