我提示一个文件名的用户,如果他们输入一个有效的文件名中的第一次,它的工作原理。但是,如果它的第一次无效,所有其他检查失败。我将如何解决这一问题?此外,让我们说,他们只指定一个目录,我怎么会得到所有的文本文件的名称和有多少?

int main() {

    ifstream inFile;
    int result;
    string filename;

    cout << "If the executable is not in the same directory as the\nfile, then a directory needs to be provided\n\n";
    while (true) {
        cout << "Enter the file name:  ";
        getline(cin, filename);
        inFile.open(filename.c_str(), ios::in);

        if (!inFile)
            cout << "\n**File failed to open**\n\n";
        else break;
    }

    result = countLOC(inFile);
    cout << "\nThere are " << result << " lines of code in \"" << filename << "\"\n\n";

    inFile.close();
    return 0;
}
有帮助吗?

解决方案

这是因为在对象“INFILE”的错误比特被置位。结果 你需要你做任何事情之前重置错误位。

if (!inFile)
{
    cout << "\n**File failed to open**\n\n";
    inFile.clear();
}
else break;

其他提示

呼叫清楚中的调用来打开前的状态复位。

您并不真正需要使用的错误标志等,你可以调用inFile.is_open()函数用于检查。您不需要使用inFile.clear()两种。

是做一个明确的

如果用户提供你需要做的一个目录的FindFirst和FindNext中

msdn.microsoft.com/en-us/library/zyzxfzac(VS.71)的.aspx

和过程的所有文件的方式。

清除它。此外,你并不需要在循环的休息,我反而认为这样的:

do {
    if (infile.fail())
       cout << "\n**File failed to open**\n\n";
    infile.clear()
    cout << "Enter the file name:  ";
    getline(cin, filename);
    inFile.open(filename.c_str(), ios::in);
} while(!infile)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top