簡體   English   中英

如何讀取兩個文件並正確關閉第一個文件? C ++

[英]How to read two files and closing the first one properly? C++

我創建了兩個文件,第一個文件包含:1 2 3 4; 第二個包含:5 6 7 8我試圖依次讀取第二個文件,但是盡管我關閉了它,但它沒有讀取第二個文件,而是再次讀取了第一個文件。

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

int main()

{

    ifstream  inFile;
     inFile.clear();
    inFile.open("text1.txt");

    if (inFile.fail())
    {
        cerr << "Error Opening File "<< endl;
        exit(1);
    }

    int first1, second1, third1, last1;

    inFile >> first1 >> second1 >> third1 >> last1;


    cout 
<< first1 << " " << second1 << " " << third1  <<  " "<<  last1 << endl;

    inFile.close();




    ifstream  inFile1;
     inFile1.clear();
    inFile1.open("text2.txt");

    if (inFile1.fail())
    {
        cerr << "Error Opening File "<< endl;
        exit(1);
    }

   int first2, second2, third2, last2;

    inFile >> first2 >> second2 >> third2 >> last2;


    cout 
<< first2 << " " << second2 << " " << third2  <<  " "<<  last2 << endl;

    inFile1.close();






    return 0;
} 

它打印

1 2 3 4
1 2 3 4

代替

1 2 3 4
5 6 7 8

我究竟做錯了什么?

您第二次從inFile而不是inFile1獲取數據。

inFile >> first2 >> second2 >> third2 >> last2;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM