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

2025-05-27 0 81

Read函数定义

通过read函数将文件中的数据按照一定的长度读取出来并且存放在新的数组中。用于从文件中读取数据。

函数原型istream& read (char* s, streamsize n);

参数char* s取出数据的流向的char类型数组指针,streamsize n表示数组的长度

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
#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函数使用例子

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30
#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;

}

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++ read函数读入int整形数据 https://www.kuaiidc.com/74671.html

相关文章

发表评论
暂无评论