C++ read函數讀入int整形數據。本站提示廣大學習愛好者:(C++ read函數讀入int整形數據)文章只能為提供參考,不一定能成為您想要的結果。以下是C++ read函數讀入int整形數據正文
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::ifstream int 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."; else std::cout << "error: only " << is.gcount() << " could be read"; is.close(); // ...buffer contains the entire file... delete[] buffer; } return 0; }