user588877
user588877

Reputation:

How to read integer value from file in C++

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?

Upvotes: 4

Views: 23450

Answers (4)

Stephane Rolland
Stephane Rolland

Reputation: 39926

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()

Upvotes: -2

user467871
user467871

Reputation:

ifstream file;
file.open("text.txt");

int i;

while (file >> i) {
   cout << i << endl;
}

Upvotes: 5

baris.aydinoz
baris.aydinoz

Reputation: 1950

ifstream f;
f.open("text.txt");

if (!f.is_open())
  return;

std::vector<int> numbers;
int i;

while (f >> i) {
 numbers.push_back(i);
}

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363817

ifstream f(filename);

int x, y, z;
f >> x >> y >> z;

Upvotes: 2

Related Questions