Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Đọc dữ liệu từ file text bằng C++

Đây là chương trình C++ đọc dữ liệu từ file text.

Đầu vào

tpoint.txt có nội dung ban đầu "Tutorials point."

Đầu ra

Tutorials point.

Thuật toán

Bắt đầu
  Tạo đối tượng newfile lớp fstream.
  Gọi open() mở "tpoint.txt" ghi dùng newfile.
  Nếu file mở được thì
    Nhập chuỗi "Tutorials point" vào tpoint.txt.
    Đóng file newfile bằng close().
  Gọi open() mở "tpoint.txt" đọc dùng newfile.
  Nếu file mở được thì
    Khai báo chuỗi "tp".
    Đọc toàn bộ dữ liệu file newfile bằng getline() đưa vào chuỗi tp.
    In dữ liệu chuỗi tp.
    Đóng file newfile bằng close().
Kết thúc.

Ví dụ

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
    fstream newfile;
    newfile.open("tpoint.txt", ios::out); // mở file ghi
    if(newfile.is_open()) // kiểm tra file mở
    {
        newfile << "Tutorials point \n"; // chèn text
        newfile.close(); // đóng file
    }
    newfile.open("tpoint.txt", ios::in); // mở file đọc
    if (newfile.is_open()){
        string tp;
        while(getline(newfile, tp)){ // đọc dữ liệu đưa vào string
            cout << tp << "\n"; // in dữ liệu string
        }
        newfile.close(); // đóng file
    }
}

Kết quả

Tutorials point