【发布时间】:2019-11-22 17:05:46
【问题描述】:
我正在尝试为家庭作业编写一个程序,该程序读取记事本文件的内容并显示文件中的内容和字数。当我输入用于测试程序的文件的名称时,我的代码当前没有输出任何内容,并且我插入的输入验证 while 循环也不起作用。
#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;
}
代码在其当前状态下编译 [但不会产生预期的结果。
【问题讨论】:
-
编译仅仅意味着它在语法上是正确的,而不是它在逻辑上是正确的。在调试器中单步调试代码将帮助您弄清楚为什么它没有按预期工作。
-
见why
while (!inData.eof())is wrong。此外,ifstream函数与std::string一起工作得很好,无需使用c_str。当流超出范围时,流析构函数将自动关闭文件,因此您不必显式关闭它。你认为这个循环有什么作用?while (fileName != "quit")见ericlippert.com/2014/03/05/how-to-debug-small-programs
标签: c++ file while-loop