Home  >  Article  >  Backend Development  >  Usage of infile in c++

Usage of infile in c++

下次还敢
下次还敢Original
2024-05-08 01:18:18901browse

ifstream is a stream object in C used to read data from files. The method of use is as follows: Create an ifstream object and specify the file path to be opened. Open the file using the open() method. Use the >> operator to read data from a file stream. Use the eof() and fail() methods to check for error conditions. Close the file stream using the close() method.

Usage of infile in c++

Usage of ifstream in C

ifstream is a stream object in C used to read data from a file. It is derived from an abstract data type called file stream and provides a convenient interface for handling file input operations.

Constructor

Creating an ifstream object requires a string parameter representing the path of the file to be opened.

<code class="cpp">ifstream infile("input.txt");</code>

Open the file

Use the open() method to open the file explicitly. If open() is not called, the file must be opened explicitly before reading it using ifstream.

<code class="cpp">infile.open("input.txt");</code>

Reading data

You can use the >> operator to read data from a file stream. It reads data into variables.

<code class="cpp">int number;
infile >> number;</code>

Error handling

ifstream provides eof() and fail() methods to check error conditions. eof() checks for end of file, while fail() checks for other errors.

<code class="cpp">if (infile.eof()) {
  // 文件结束
} else if (infile.fail()) {
  // 发生错误
}</code>

Close the file

Use the close() method to close the file stream and release system resources.

<code class="cpp">infile.close();</code>

Example

Here is an example showing how to read numbers from a file using ifstream:

<code class="cpp">#include <iostream>
#include <fstream>

using namespace std;

int main() {
  ifstream infile("input.txt");

  int number;
  infile >> number;

  cout << "读取的数字: " << number << endl;

  infile.close();

  return 0;
}</code>

The above is the detailed content of Usage of infile in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn