2017-01-06 18 views
0

임의의 .txt 파일을 열고 일부 문자열에 데이터를 넣으 려합니다. 코드에 경로를 쓰면 작동합니다.ifstream + 임의의 txt 파일 열기 (c_str)

왜 이런 식으로 작동하지 않는 지 알 수 없습니다.

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    string file; 

    ifstream filein(file.c_str()); 

    cout << "Insert Path" << endl; 
    cin >> file; 

    cout << file << endl; 

    filein.open(file.c_str(), ios::in); 

    for (string line; getline(filein, line);) { 
     cout << line << endl; 
    } 

    return 0; 
} 
+1

디버거에서 실행했을 때'파일 '은 무엇입니까? 그게 뭐야? –

답변

2

std::string이 기본값이므로 파일 이름 문자열이 비어 있습니다.

ifstream 생성자에 빈 문자열 (또는 널 문자열)을 전달하는 것이 가장 좋고 정의되지 않은 동작입니다.

0

하는 것은 다음과 같은 코드를 작성하십시오 :

#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 호환 컴파일러가있는 경우

, 당신이 대신과 같은 코드를 작성 제안하는거야 객체는 코드를 읽기 쉽도록 만들고 오류를보다 명확하게 지정하고 액세스 할 수없는 동작에 대한 액세스 권한을 부여합니다.

+0

그래서, 왜 누군가가 그런 코드를 작성해야합니까? 이것은 영업 이익을 위해 무엇을합니까? 답안 코드와 OP의 차이와 같은 설명을 사용하여 답을 편집하십시오. –

+0

@ThomasMatthews 그냥 했어. – Xirema

+0

왜 디폴트로'ifstream'을 구성합니까? 'std :: string filename;을 사용하면 쉽게 만들 수 있습니다. std :: cin >> filename; std :: ifstream fin (파일 이름)'. – NathanOliver

0

처음 열어 본 무엇입니까? 당신은 문자열이 아무것도 포함하지 않는 한?

초 문자열에 유효한 경로가 포함되어 있고 처음 열 때 성공했지만 두 번째 파일은 버퍼를 지우지 않고 이전 파일을 닫지 않고 동일한 파일 스트림을 여러 파일에 사용하는 경우 실패합니다.

string file "C:\\MyProject\\data.txt"; // let's say a valid path 

ifstream filein(file.c_str()); 

if(filein.fail()) // the condition fails as long as the opening was successfull 
    cout << "failed to open file!" << endl; 

cout << "Insert Path" << endl; 
cin >> file; // let's say the user enters a valid path again: "C:\\MyProject\\test.txt" 

cout << file << endl; 

filein.open(file.c_str(), ios::in); // fail to correct it: 

filein.close(); 
filein.clear(); // very important 

filein.open(file.c_str(), ios::in); // now it's ok! 

for (string line; getline(filein, line);) { 
    cout << line << endl; 
}