尝试像这样编写代码:
#include <iostream>
#include <fstream>
int main()
{
std::string file;
std::cout << "Insert Path" << std::endl;
std::getline(std::cin, file);
std::cout << file << std::endl;
std::ifstream filein(file);
for (std::string line; std::getline(filein, line); )
{
std::cout << line << std::endl;
}
return 0;
}
值得注意的编辑包括:
- 我们现在
ifstream
只在需要时构建对象,在file
存储了数据之后,这意味着不再有未定义的行为,并且我们只在知道路径是什么之后才尝试打开文件。
- 我们在存储到时检索一整行
file
,而不是仅检索第一个单词,如果您的路径包含任何空格,这一点至关重要。
- 我们只是
file
直接使用字符串。没有必要打电话c_str()
。
- 我们不再使用
using namespace std;
. 为什么这是不好的做法有很多很多原因。
编辑:
如果你有一个兼容 C++17 的编译器,我建议你编写如下代码:
#include <iostream>
#include <fstream>
//You may need to write #include <experimental/filesystem>
#include <filesystem>
#include <string>
int main()
{
std::string input_line;
std::cout << "Insert Path" << std::endl;
std::getline(std::cin, input_line);
//You may need to write std::experimental::filesystem
std::filesystem::path file_path{input_line};
//This will print the "absolute path", which is more valuable for debugging purposes
std::cout << std::filesystem::absolute(file_path) << std::endl;
std::ifstream filein(file_path);
for (std::string line; std::getline(filein, line); )
{
cout << line << endl;
}
return 0;
}
显式使用path
对象将使您的代码更具可读性并使错误更加明确,并授予您访问原本无法访问的行为的权限。