1-标准输入流.cpp
#include <iostream>
using namespace std;
int main()
{
char ch;
char buf[32] = {0};
/*cin >> ch;
cout << ch << endl;
ch = cin.get();
cout << ch << endl;
cin.get(ch);
cout << ch << endl;
cin.get(buf, 10); //获取字符串,最多10个字节
cout << buf << endl;
cin.getline(buf, 10); //获取一行数据,最多10个字节
cout << buf << endl;
cin.ignore(5); //忽略前5个字节
cin >> buf;
cout << buf << endl;
ch = cin.peek(); //获取一个字符,同时字符还留在缓冲区
cout << ch << endl;
cin >> buf;
cout << buf << endl;*/
cin >> ch;
cin.putback(ch); //把ch放回缓冲区
cin >> buf;
cout << buf << endl;
return 0;
}
2-标准输出流.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
#if 0
//使用控制符的方法
int num = 1000;
cout << oct << num << endl; //八进制输出
cout << dec << num << endl; //十进制输出
cout << hex << num << endl; //十六进制输出
cout << setbase(8) << num << endl;
double PI = 222.0000 / 7.00000;
cout << PI << endl;
cout << setprecision(15) << PI << endl;
cout << setprecision(5) << setiosflags(ios::scientific) << PI << endl;
const char *s = "helloworld";
cout << setw(15) << setfill('*') << s << endl;
#endif
//使用成员函数的方式
int num = 1000;
cout.unsetf(ios::dec); //结束十进制格式输出
cout.setf(ios::oct); //设置八进制格式输出
cout << num << endl;
cout.unsetf(ios::oct);
cout.setf(ios::hex);
cout << num << endl;
double PI = 222.000 / 7.000;
cout.precision(5);
cout << PI << endl;
cout.setf(ios::scientific);
cout << PI << endl;
const char *s = "helloworld";
cout.width(15);
cout.fill('^');
cout << s << endl;
return 0;
}
3-文件读写操作.cpp
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main()
{
#if 0
char buf[32] = "helloworld";
ofstream ofs; //创建输出流对象(写文件)
ofs.open("hello.txt", ios::out); //使用默认参数 默认是输出格式 ios::out
ofs << buf; //使用输出运算符把buf写入文件 buf >> ofs不可以这样使用
ofs.close();
memset(buf, 0, sizeof(buf));
ifstream ifs("hello.txt"); //创建输入流对象(读文件) 通过构造函数,打开文件
ifs >> buf;
cout << buf << endl;
ifs.close();
#endif
char buf[32] = "helloworld";
fstream fs("hello.c", ios::out); //out含有创建的属性
fs.write(buf, strlen(buf));
fs.close();
char ch;
memset(buf, 0, sizeof(buf));
fs.open("hello.c", ios::in); //输入(读)的方式打开文件
//fs.read(buf, sizeof(buf));
while ((ch = fs.get()) != EOF) //end of file
{
cout << ch;
}
cout << endl;
//cout << buf << endl;
fs.close();
return 0;
}

本文详细介绍了C++中标准输入输出流的使用方法,包括字符读取、字符串读写、格式化输出等,以及如何进行文件的读写操作,如打开、关闭文件,读写字符和字符串。

5339

被折叠的 条评论
为什么被折叠?



