하는 것은 다음과 같은 코드를 작성하십시오 :
#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;
을 사용하고 있지 않습니다. 왜 이것이 나쁜 행동인지 many, many reasons이 있습니다.
편집 :
#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
을의 : 당신이 C++ 17 호환 컴파일러가있는 경우
, 당신이 대신과 같은 코드를 작성 제안하는거야 객체는 코드를 읽기 쉽도록 만들고 오류를보다 명확하게 지정하고 액세스 할 수없는 동작에 대한 액세스 권한을 부여합니다.
디버거에서 실행했을 때'파일 '은 무엇입니까? 그게 뭐야? –