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

How Do I read and Output the Contents of a File and the Number of Words it Contains?

本文关键字:包含 文件 何读取 读取 输出      更新时间:2023-10-16

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

#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 << " datan";
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;
}

代码在其当前状态下编译 [但不产生所需的结果。

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

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

然后,一开始听起来很容易的事情,数数字数,其实并不那么容易。什么是词?仅字符,还是与数字甚至下划线混合的字符,例如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;
}

希望这有帮助。 。 。

相关文章: