//cin.get
void test01(){
#if 0
char ch = cin.get();
cout << ch << endl;
cin.get(ch);
cout << ch << endl;
//链式编程
char char1, char2, char3, char4;
cin.get(char1).get(char2).get(char3).get(char4);
cout << char1 << " " << char2 << “” << char3 << " " << char4 << " ";
#endif
char buf[1024] = { 0 };
//cin.get(buf.1024);
cin.getline(buf,1024);
cout << buf;
}
//cin.ignore
void test02(){
char buf[1024] = { 0 };
cin.ignore(2); //忽略缓冲区当前字符
cin.get(buf,1024);
cout << buf << endl;
}
//cin.putback 将数据放回缓冲区
void test03(){
//从缓冲区取走一个字符
char ch = cin.get();
cout << “从缓冲区取走的字符:” << ch << endl;
//将数据再放回缓冲区
cin.putback(ch);
char buf[1024] = { 0 };
cin.get(buf,1024);
cout << buf << endl;
}
//cin.peek 偷窥
void test04(){
//偷窥下缓冲区的数据
char ch = cin.peek();
cout << “偷窥缓冲区数据:” << ch << endl;
char buf[1024] = { 0 };
cin.get(buf, 1024);
cout << buf << endl;
}
//练习 作业 使用cin.get和putback完成类似功能
void test05(){
cout << “请输入一个数字或者字符串:” << endl;
char ch = cin.peek();
if(ch >= ‘0’ && ch <= ‘9’){
int number;
cin >> number;
cout << “数字:” << number << endl;
}
else{
char buf[64] = { 0 };
cin.getline(buf, 64);
cout << “字符串:” << buf << endl;
}
}
1.字符输出
//cout.flush 刷新缓冲区,linux下有效
void test01(){
cout << “hello world”;
//刷新缓冲区
cout.flush();
}
//cout.put 输出一个字符
void test02(){
cout.put(‘a’);
//链式编程
cout.put(‘h’).put(‘e’).put(‘l’);
}
//cout.write 输出字符串 buf,输出多少个
void test03(){
//char* str = “hello world!”;
//cout.write(str, strlen(str));
char* str = “*************”;
for (int i = 1; i <= strlen(str); i ++){
cout.write(str, i);
cout << endl;
}
for (int i = strlen(str); i > 0; i --){
cout.write(str, i);
cout << endl;
}
}
2.格式化输出
使用流对象的有关成员函数
控制符格式化输出
C++提供了在输入输出流中使用的控制符(有的书中称为操纵符)。
//通过流成员函数
void test01(){
int number = 99;
cout.width(20);
cout.fill(‘*’);
cout.setf(ios::left);
cout.unsetf(ios::dec); //卸载十进制
cout.setf(ios::hex);
cout.setf(ios::showbase);
cout.unsetf(ios::hex);
cout.setf(ios::oct);
cout << number << endl;
}
//使用控制符
void test02(){
int number = 99;
cout << setw(20)
<< setfill(‘~’)
<< setiosflags(ios::showbase)
<< setiosflags(ios::left)
<< hex
<< number
<< endl;
}