0

这很容易,但我现在正在画一个空白(漫长的一天)。如果输入的文件名无效或错误,我只需要这部分代码来重新提示输入文件名。

cout << "Please enter a file name:" << endl;
string filename;
string line;
cin >> filename;
ifstream in_file;
in_file.open(filename.c_str());


    if (in_file.good())
    {
        getline (in_file, line);
        cout << line << endl;
        in_file.close();
    }
4

3 回答 3

4

使用循环:

#include <iostream>
#include <sstream>
#include <string>

for (std::string filename;
     std::cout << "Enter filename: " && std::getline(std::cin, filename); )
{
    if (std::ifstream infile(filename))
    {
        std::string line;
        if (std::getline(infile, line))
        {
            std::cout << line << std::endl;
        }
        break;
    }
    std::cout << "Could not open file '" << filename << "', please try again.\n";
}

(如果您愿意,当然可以在内部操作中重用外部字符串。)

于 2013-09-27T22:41:16.717 回答
0

您希望始终执行一次操作,但如果某些条件为真,请重复执行。

所以do-while循环是正确的方法:

ifstream in_file;
string filename;
string line;

do {
    cout << "Please enter a file name:" << endl;
    cin >> filename;
    in_file.open(filename.c_str());
} while (!in_file.good());

getline (in_file, line);
cout << line << endl;
in_file.close();
于 2013-09-27T23:59:32.100 回答
0

如果有有效输入,请使用 while cicle 并打破它。

while (1) {
    cout << "Please enter a file name:" << endl;
    string filename;
    string line;
    cin >> filename;
    ifstream in_file;
    in_file.open(filename.c_str());


    if (in_file.good())
    {
        getline (in_file, line);
        cout << line << endl;
        in_file.close();
        break; // breaks the while
    }
}
于 2013-09-27T22:38:57.670 回答