【问题标题】:Prompting a user for the filename or directory提示用户输入文件名或目录
【发布时间】:2009-05-20 22:45:20
【问题描述】:

我正在提示用户输入文件名,如果他们第一次输入有效的文件名,它会起作用。但是,如果第一次无效,则其他所有检查都会失败。我将如何解决这个问题?另外,假设他们只是指定一个目录,我将如何获取所有文本文件的名称以及有多少?

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;
}

【问题讨论】:

    标签: c++ file filenames istream


    【解决方案1】:

    这是因为对象“inFile”中的错误位已设置。
    在执行任何其他操作之前,您需要重置错误位。

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

    【讨论】:

      【解决方案2】:

      调用clear重置调用打开前的状态。

      【讨论】:

        【解决方案3】:

        您实际上不需要使用错误标志等,您可以调用 inFile.is_open() 函数进行检查。您也不需要使用 inFile.clear()。

        【讨论】:

          【解决方案4】:

          是的,做个清楚

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

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

          并以这种方式处理所有文件。

          【讨论】:

            【解决方案5】:

            清除它。此外,您不需要循环中的中断,我建议您这样做:

            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)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-04-30
              • 2012-03-30
              • 1970-01-01
              • 1970-01-01
              • 2016-09-26
              • 2020-12-09
              • 1970-01-01
              • 2016-01-30
              相关资源
              最近更新 更多