使用 ifstream,被调用文件中的数据不打印

Working with ifstream, data within file being called does not print

这是我的代码,目标是打开一个文件,读取该文件中的单词并计算文件中有多少字符串。我的问题是,当我 运行 我的程序并调用测试文件时,只有该文件的第一个字符串被读取和打印,我不确定它出了什么问题,任何帮助都会很好。

这是我的测试文件中的内容:

这个 &% 文件应该!!,...

正好有 7 个字。


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){

    ifstream inputFile;
    string fileName, inputRead;
    string sentinel = "quit";
    int count = 0;

    cout<< "what file do you want to open?: ";
    cin>> fileName;

    inputFile.open(fileName);

    while(!inputFile){
        cout<< "\nError opening file." <<endl;

        cout<< "Please enter filename correctly: ";
        cin>> fileName;

        inputFile.open(fileName);

    }

    while(fileName != sentinel){
        if(inputFile){

            inputFile >> inputRead;

            count++;

            cout<< endl;
            cout<< fileName << " data" <<endl;
            cout<< "*********************************\n" <<endl;

            cout<< inputRead <<endl;

            cout<< "\n*********************************" <<endl;
            cout<< fileName << " has " << count << " words." <<endl;

            cout<< "\nEnter another file name or type \"quit\" to end: ";
            cin>> fileName;
        }
    }

    inputFile.close();

    cout<< endl;

}

问题出在 while 循环中的 if 语句。如果文件名不等于 sentinel,则检查 inputFile 是否有效。如果是这样,您只需在获取新文件名之前执行一次内部代码行。你想要的是这样的:

while(fileName != sentinel){
    cout<< endl;
    cout<< fileName << " data" <<endl;
    cout<< "*********************************\n" <<endl;
    while(inputFile >> inputRead){

        count++;


        cout<< inputRead <<endl;

    }
    cout<< "\n*********************************" <<endl;
    cout<< fileName << " has " << count << " words." <<endl;

    cout<< "\nEnter another file name or type \"quit\" to end: ";
    cin>> fileName;
}