Read函數定義
通過read函數將文件中的數據按照一定的長度讀取出來并且存放在新的數組中。用于從文件中讀取數據。
函數原型istream& read (char* s, streamsize n);
參數char* s取出數據的流向的char類型數組指針,streamsize n表示數組的長度
#include<iostream>using namespace std;int read()//read函數主體部分{ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9') { if(ch=='-')f=-1; ch=getchar(); } while(ch>='0'&&ch<='9') { x=x*10+ch-'0'; ch=getchar(); } return x*f;}int main(){ int n=read()//這就是讀入了n(注意只能用來讀入int類型的數據,long long還需更改) system("pause"); return 0;}
Read函數使用例子
#include <iostream> // std::cout#include <fstream> // std::ifstreamint main () {std::ifstream is ("test.txt", std::ifstream::binary);if (is) {// get length of file:is.seekg (0, is.end);int length = is.tellg();is.seekg (0, is.beg);char * buffer = new char [length];std::cout << "Reading " << length << " characters... ";// read data as a block:is.read (buffer,length);if (is)std::cout << "all characters read successfully.";elsestd::cout << "error: only " << is.gcount() << " could be read";is.close();// ...buffer contains the entire file...delete[] buffer;}return 0;}
新聞熱點
疑難解答