这很容易,但我现在正在画一个空白(漫长的一天)。如果输入的文件名无效或不好,我只需要这部分代码重新提示文件名。
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();
}
答案 0 :(得分: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";
}
(如果你愿意,你当然可以在内部操作中重用外部字符串。)
答案 1 :(得分: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
}
}
答案 2 :(得分: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();