如何在我的c ++程序中打印文件并取出文字?

时间:2010-10-06 00:58:46

标签: c++

我正在用c ++编写程序,我需要向用户询问文件名,打印文件然后重新打印,每5个字丢失一次。我已经知道要问他们文件名,检查错误并打印出文件,我只是完全迷失了如何在每5个字丢失的情况下重新打印它,有什么帮助吗?

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

int main()

{   

const int SIZE = 51;

    char fileName[SIZE];

char ch;

ifstream inFile;

bool lastWasLetter = true;

const string UNDERLINE  = "__________";

cout << "Please enter a file name: ";

cin >> fileName;

inFile.open (fileName, ios::in);
while (!inFile)
{
    cout << fileName << " could not be opened, please enter new file name: ";
    cin >> fileName ;
    inFile.open (fileName, ios::in);
}

inFile.clear();               // reset read pointer to very beginning of file
    inFile.seekg(0L, ios::beg); 

    std::string word;
int count = 0;

while (inFile >> word)
{
 count++;
 if (count % 5 != 0)
      cout << word << endl;
}
}

是的,这是我正在为我的编程课工作的一个项目。

1 个答案:

答案 0 :(得分:0)

只需跟踪您已阅读的单词数量,并跳过每隔5个单词打印一次,即每当单词计数为5的倍数时。例如:

std::string word;
int count = 0;

while (inFile >> word) {
  count++;
  if (count % 5 != 0)
    cout << word << endl;
}