如何暂时打开和关闭文件

时间:2019-03-17 06:39:56

标签: c++

我需要这个程序来显示文件(文本文件)中的单词数。但是,请不要重置文字计数器。它应该是7,但显示62个字。有人告诉我从倒数第二个关闭该文件,然后创建一个新的while(最后一个),然后再次打开该文件。我已经为此工作了一段时间。但是,进行更改后,它将不再显示文件。屏幕上唯一显示的是单词和2个单词的帐户。     谢谢您的帮助

helpData.php

1 个答案:

答案 0 :(得分:0)

你想要这个吗?

#include<iostream>
#include<fstream>//step#1
#include<string>

using namespace std;

int main() {
   string word,fileName;
   char character;
   int charcounter = 0, wordcounter = 0;
   ifstream inData;// incoming file stream variable

   cout << " Enter filename or type quit to exit: ";
   cin >> fileName;

   //loop to allow for multiple files data reads
   while (fileName != "quit")
   {
      inData.open(fileName.c_str());//open file and bind file to ifstream variable

      //loop for file not found validation
      while (!inData)//filestream is in fail state due to no file
      {
         inData.clear();//clear the fail state
         cout <<"File not found. Enter the correct filename: ";
         cin >> fileName;
         inData.open(fileName.c_str());
      }


      cout << "\n*****************************\n";
      while (inData)
      {
         inData >> character;//extract a single character from the file
         cout << character;
         charcounter++;
      }

      cout << "\n******************************\n";
      cout << fileName << " has " << charcounter << " chars." << endl;
      inData.close();//close the ifstream conection to the data file

      inData.open(fileName.c_str());
      while (inData)
      {
         inData >> word;
         cout << word;
         wordcounter++;
      }
      cout << "\n******************************\n";
      cout << fileName << " has " << wordcounter << " words." << endl;
      inData.close();//close the ifstream conection to the data file


      charcounter = 0; //reset character count
      wordcounter = 0;
      //port for next file or exit
      cout << "Enter a filename or type quit to exit: ";
      cin >> fileName;
   }

   return 0;
}