如何读取和输出文件的内容及其包含的单词数?

时间:2019-07-13 00:31:10

标签: c++ file while-loop

我正在尝试编写一个作业程序,该程序读取记事本文件的内容并显示内容和该文件中的单词数。当我输入用于测试程序的文件名时,我的代码当前什么也不输出,并且在插入循环时进行的输入验证也不起作用。

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

int main()
{
//Declare needed variables
string fileName, contents;

int wordCount = 0;
ifstream inData;

//Display program info
cout << "*** A SIMPLE FILE PROCESSING PROGRAM ***" << endl;

//Prompt user input
cout << "Enter a filename or type quit to exit: ";
cin >> fileName;

inData.open(fileName.c_str());

//Inform the user when their input is invalid and ask them to input another 
file name
while (!inData)
{
    inData.clear();
    inData.ignore(200, '\n');
    cout << "File not found. Please type a correct file name." << endl;
    cin >> fileName;
    inData.open(fileName.c_str());
}

inData >> contents;

//Read and output the contents of the selected file
while (inData)
{
    cout << fileName << " data\n";
    cout << "***********************" << endl;
    inData >> contents;
    wordCount++;
    cout << contents << endl;
    inData >> contents;
}

//Display the number of words in the file
cout << "***********************" << endl;
cout << fileName << " has " << wordCount << " words." << endl;

inData.close();

return 0;
}

代码以其当前状态编译[但不会产生预期的结果。

1 个答案:

答案 0 :(得分:0)

我将向您展示许多可能的解决方案之一。

但是我不建议在循环中检查文件名的有效性。您不会给用户逃脱的机会。因此,我建议打开文件,如果不起作用,则显示错误消息并退出。

然后,一开始听起来很简单,算上单词,并不是那么容易。什么字像C ++变量名一样,仅包含字符,还是包含数字甚至下划线的字符?需要定义。

此外,您可能还会使用逗号或一个或多个其他空格等分隔符。因此,像"Hello,,,,World"这样的行很难被计数。如果您尝试阅读这两个单词,那么您会发现一个惊喜。

    std::string s1{};
    std::string s2{};
    std::istringstream iss("Hello,,,,World");
    iss >> s1 >> s2;

将读取s1中的所有内容!

解决方案是我们明确定义单词是什么。而我们将使用std::regex完成此操作。在下面的示例中,我们使用字符,数字和_

然后,我们使用regex_iterator查找该行中所有出现的正则表达式(单词)。我们从头开始用std::distance减去结尾,这将使我们对单词进行计数。

然后我们以任何格式将输出提供给用户。

这似乎很复杂。但这是精确的。而且相当灵活。尝试逐行分析,您会理解的。

请参阅:

#include <iostream>
#include <string>
#include <regex>
#include <fstream>
#include <iomanip>

int main()
{
    // Get a filename from the user
    std::cout << "Enter a filename:\n";
    std::string filename{};  std::cin >> filename;

    // Try to open and read the file
    std::ifstream fileStream(filename);
    if (fileStream) {
        // We will count all words
        size_t numberOfWordsOverall{ 0 };

        // We will also count the lines in the file
        size_t lineCounter{ 1 };

        // Define, what a word is. In this case: Characters, Digits and _
        std::regex regexForWord("[\\w\\d_]+");

        // Read all lines in file
        std::string line{};
        while (std::getline(fileStream, line)) {

            // Count the numbers of words in one line
            const size_t numberOfWordsInLine = std::distance(
                std::sregex_token_iterator(line.begin(), line.end(), regexForWord, 1),
                std::sregex_token_iterator()
            );
            // Update the overall word counter
            numberOfWordsOverall += numberOfWordsInLine;

            // Show result to user
            std::cout << "# " << std::left << std::setw(2) << lineCounter++ << "   (Words in line: "<< std::setw(2) << numberOfWordsInLine <<
                " Words overall: " << std::setw(4) << numberOfWordsOverall << ")  Line content --> " << line << '\n';
        }
    }
    else {
        std::cerr << "Could not open file '" << filename << "'\n";
    }
    return 0;
}

希望这会有所帮助。 。 。