要求文件名

时间:2014-04-02 19:10:37

标签: c++ input

样品

请输入文件名:out
打开文件时出错。请再试一次。请提供文件名:在 打开文件时出错。请再试一次。请给出文件名:inpou错误打开文件。请再试一次。 请确保您尝试打开的文件存在。

请输入文件名:input.txt

void name()

{
    char fname [40];
    done=false;

    do {
        cout<< "Please give the filename: ";
        cin.getline(fname, sizeof(fname));
        infile.open(fname);
            if (infile.fail()){
                cout<< "Error opening file. Please try again.";
                infile.clear();

            }
            else done= true;
            cout<<endl;
            }
    while(!done);


}

我需要告诉用户&#34;请确保您尝试打开的文件存在。 &#34;在每三次尝试失败后。任何建议我都不确定如何使其发挥作用。

2 个答案:

答案 0 :(得分:1)

您可以包含一个在每次无效文件打开尝试时递增的计数器。一旦检查存储在计数器中的值是否是第三次尝试,您就可以发出消息。

答案 1 :(得分:0)

这可能是一个示例实现:

#include <iostream>
#include <fstream>

std::string name()
{
    for (int tryCount = 0;; ++tryCount) {
        char fileName[1024];
        std::cout << "Please give the filename: ";
        std::cin.getline(fileName, sizeof(fileName));
        std::ifstream infile(fileName);
        if (infile.fail()) {
            std::cout << "Error opening file. Please try again." << std::endl;
            if (tryCount % 3 == 2) {
                std::cout << "Please make sure the filename is correct." << std::endl;
            }
            infile.clear();
        } else {
            return std::string(fileName);
        }
    }
}

int main()
{
    std::cout << name();
}