一、基于控制台的I/O
我们所熟悉的输入输出操作分别是istream(输入流)和ostream(输出流)这两个类提供的,为了允许双向的输入/输出,有istream和ostream派生出了iostream类。cin是 istream的实例,cout是ostream的实例。
二、基于文件的I/O
#include "iostream"
#include<fstream>
using namespace std;
void main()
{
fstream f("d:\\try.txt", ios::out);//供写使用,文件不存在则创建,存在则清空原内容
f << 1234 << ' ' << 3.14 << 'A' << "How are you"; //写入数据
f.close();//关闭文件以使其重新变为可访问,函数一旦调用,原先的流对象就可以被用来打开其它的文件
f.open("d:\\try.txt", ios::in);//打开文件,供读
int i;
double d;
char c;
char s[20];
f >> i >> d >> c; //读取数据
f.getline(s, 20);
cout << i << endl; //显示各数据
cout << d << endl;
cout << c << endl;
cout << s << endl;
f.close();
}
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <vector>
using namespace std;
int main()
{
char buffer[256];
ifstream in("input.txt");//文件不存在会返回错误
if (!in.is_open())
{
cout << "Error opening file" << endl;
exit(1);
}
vector<string> a;
while (!in.eof())
{
in.getline(buffer, 100);
//cout << buffer << endl;
a.push_back(buffer);
}
for (unsigned int i = 0; i < a.size(); i++)
cout << a[i].c_str()<< endl;
return 0;
}
三、基于字符串的I/O
#include <string>
#include <sstream>//
#include <iostream>
//ostringstream 用于执行C风格字符串的输出操作
void ostringstream_test()
{
//ostringstream 只支持 << 操作符
std::ostringstream oss;
oss << "this is test" << 123456;
oss.str("");//清空之前的内容
//oss.clear();//并不能清空内存
//浮点数转换限制
double tmp = 123.1234567890123;
oss.precision(12);
oss.setf(std::ios::fixed);//将浮点数的位数限定为小数点之后的位数
oss << tmp;
std::cout << oss.str() << "\r\n" << std::endl;
}
//istringstream 用于执行C风格字符串的输入操作
void istringstream_test()
{
//istringstream 只支持 >> 操作符
std::string str = "welcome to china";
std::istringstream iss(str);
//把字符串中以空格隔开的内容提取出来
std::string out;
while (iss >> out)
{
std::cout << out << std::endl;
}
std::cout << "\r\n" << std::endl;
}
//stringstream 同时支持C风格字符串的输入输出操作
void stringstream_test()
{
//输入
std::stringstream ss;
ss << "hello this is kandy " << 123;
std::cout << ss.str() << "\r\n" << std::endl;
//输出
std::string out;
while (ss >> out)
{
std::cout << out.c_str() << std::endl;
}
std::cout << "\r\n" << std::endl;
}
int main()
{
ostringstream_test();
istringstream_test();
stringstream_test();
system("pause");
return 0;
}