4.输入输出流

来源:互联网 发布:一加二线刷包驱动端口 编辑:程序博客网 时间:2024/05/16 09:23

1、get系列函数

#include<iostream>#include<string>using namespace std;int main(){string str;cout << "输入字符串;" << endl;getline(cin, str);cout << str << endl;char sz[60];int n = cin.get();cin.getline(sz, 60);cout << n << endl;cout << sz << endl;}

2、文件读写

#include<iostream>#include<fstream>using namespace std;struct stu{char name[20];int grade;};int main(){char sz[80];fstream in;in.open("D:/project2013/STL/4inputoutput/a.txt"); //ifstream in("D:\\project2013\\STL\\a.txt"); 另一种打开方式if (!in)return 0;while (in.getline(sz, 80)){cout << sz << endl;}in.close();ofstream out;out.open("D:/project2013/STL/4inputoutput/b.txt");stu st1 = { "xiao", 65 };stu st2 = { "gao", 0 };out << st1.name << "\t" << st1.grade << endl;out << st2.name << "\t" << st2.grade << endl;out.write((const char*)&st1, sizeof(stu));out << endl;out.write((const char*)&st2, sizeof(stu));out.close();system("pause");}


3、字符串输入输出流

#include<iostream>#include<sstream>#include<string>using namespace std;int main(){int n;float f;string strHello;string strText = "1 3.14 hello";istringstream s(strText);s >> n;s >> f;s >> strHello;cout << "n=" << n << endl;cout << "f=" << f << endl;cout << "strHello=" << strHello << endl;int i;float k;string str;cout<< "input int float string:";cin >> i >> k;getline(cin, str);ostringstream os;os << "int:\t" << i << endl;os << "float:\t" << k << endl;os << "string:\t" << str << endl;string result = os.str();cout << result << endl;}


0 0