加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++ read函数读入int整形数据

发布时间:2020-12-16 05:22:51 所属栏目:百科 来源:网络整理
导读:Read函数定义 通过read函数将文件中的数据按照一定的长度读取出来并且存放在新的数组中。用于从文件中读取数据。 函数原型istream 参数char* s取出数据的流向的char类型数组指针,streamsize n表示数组的长度 #includeiostreamusing namespace std;int read(

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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读