How to read integer value from file in C++

18,874

Solution 1

It's really rare that anyone reads a file Byte by Byte ! ( one char has the size of one Byte).

One of the reason is that I/O operation are slowest. So do your IO once (reading or writing on/to the disk), then parse your data in memory as often and fastly as you want.

ifstream inoutfile;
inoutfile.open(filename)

std::string strFileContent;
if(inoutfile)
{
    inoutfile >> strFileContent; // only one I/O
}

std::cout << strFileContent; // this is also one I/O

and if you want to parse strFileContent you can access it as an array of chars this ways: strFileContent.c_str()

Solution 2

ifstream f(filename);

int x, y, z;
f >> x >> y >> z;
Share:
18,874
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    How can read integer value from file? For example, these value present in a file:

    5 6 7
    

    If I open the file using fstream then how I can get integer value?

    How can read that number and avoid blank space?