C + + read function reads int shaping data _c language

Source: Internet
Author: User
Tags function definition function prototype

Read function definition

The read function reads the data in a file to a certain length and stores it in a new array. Used to read data from a file.

Function prototype istream& read (char* s, streamsize N);

Parameter char* s The char type array pointer to the flow of the data, Streamsize n indicates the length of the array

#include <iostream>
using namespace std;
int read ()//read function body part
{
  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 ()//This is read n (note that you can only read data of type int, long long also need to change)
  system ("pause");
  return 0;
}

Use example of the Read function

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.