cin相關方法
-
cin.get() 讀出一個字符
-
cin.get(數組,數組長度) 讀出指定長度的字符到數組
-
cin.getline(數組,數組長度) 讀出一行字符串 直到\n前
-
cin.peek() 查看緩衝器,首元素,但不讀出
-
cin.putback() 將一個讀出的元素返回緩衝器原來位置
-
cin.ignore([字符個數,‘符號’]) 忽略指定的字符前,指定的字符個數;用於清理緩衝器cin.ignore(1024,’\n’),不寫參數默認去掉第一個字符
-
簡單案例
#include<iostream>
using namespace std;
#include <stdlib.h>
int main(){
char ch;
char buf[256]={0};
#if 0
ch= cin.get();
cout << ch << endl;
cin.get(buf,256);
cout << buf << endl;
cin.getline(buf,256);
cout << buf << endl;
ch=cin.peek();
cin >> buf;
if(ch>='0'&&ch<='9'){
cout << "輸入的數字" << buf <<endl;
}else{
cout << "輸入的字符串" << buf <<endl;
}
#endif
ch=cin.get();
if(ch>='0'&&ch<='9'){
cin.putback(ch);
cin >> buf;
cout << "輸入的數字" << buf <<endl;
}else{
cin.putback(ch);
cin >> buf;
cout << "輸入的字符串" << buf <<endl;
}
system("pause");
}
cout方法
- cout.flush() 刷新緩衝器
- cout.put(‘字符’) 輸出一個字符 可cout.put().put()
- cout.write(const char * str, int n) 輸出字符串 字符串、長度strlen(str)
- 格式化輸出
- 成員函數手段
cout.unsetf(ios::dec);//卸載10進制
cout.setf(ios::oct);//使用8進制輸出 16 hex
cout.setf(ios::showbase);//顯示8進制0或16 0x
cout.width(寬度);//輸出寬度
cout.fill('*');//填充字符
cout.self(ios::left);//左對齊10***
cout.self(ios::right);//***10
- 操作符手段
#include <iostream>
#include <stdlib.h>
#include <iomanip>//一定要引入
using namespace std;
int main(){
int num = 10;
cout << oct
<< setiosflags(ios::showbase)
<< setw(10)
<< setfill('*')
<< setiosflags(ios::left)
<< num
<< endl;
system("pause");
}
文本文件讀寫
#include<iostream>
#include<fstream>
using namespace std;
int main(){
char* fileName = "main.cpp";
char* fileNameOut = "mainCopy.cpp";
char ch;
ifstream ism(fileName,ios::in);
ofstream osm(fileNameOut,ios::out | ios::app);//追加
if(!ism){
cout << "文件打開失敗" << endl;
}
while(ism.get(ch)){
cout << ch;
osm.put(ch);
};
ism.close();
osm.close();
}
對象序列化和反序列化-讀寫二進制文件
#include<iostream>
#include<fstream>
using namespace std;
#include <stdlib.h>
class Person{
public:
Person(){};
Person(int age):age(age){
}
void show(){
cout << this->age << endl;
}
int age;
};
int main(){
char* fileNameOut = "mainCopy.cpp";
Person p1(10),p2(20),p3;
ofstream osm(fileNameOut,ios::out | ios::binary);//二進制
osm.write((char*)&p1,sizeof(Person));
osm.write((char*)&p2,sizeof(Person));
osm.close();
ifstream ism(fileNameOut,ios::in | ios::binary);
ism.read((char*)&p3,sizeof(Person));
p3.show();
system("pause");
}