문제

나는 여기에 IFStream 질문을 모두 마쳤으며 여전히 간단한 텍스트 파일을 읽는 데 어려움을 겪고 있습니다. Visual Studio 2008과 함께 일하고 있습니다.

내 코드는 다음과 같습니다.

// CPPFileIO.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <fstream>
#include <conio.h>
#include <iostream>
#include <string>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{

    ifstream infile;
    infile.open("input.txt", ifstream::in);

    if (infile.is_open())
    {
        while (infile.good())
            cout << (char) infile.get();
    }
    else
    {
        cout << "Unable to open file.";
    }
    infile.close();
    _getch();
    return 0;
}

나는 그것을 확인했다 input.txt 파일은 값을 확인하여 올바른 "작업 디렉토리"에 있습니다. argv[0]. 열린 메소드는 작동하지 않습니다.

나는 또한 디버깅에 문제가 있습니다. 시계를 설정할 수 없다면 infile.good() 또는 infile.is_open()? 나는 계속 받고있다

Error: member function not present.

편집하다: .CPP 파일에서 전체 코드로 업데이트 된 코드 목록.

업데이트: 파일은 현재 작업 디렉토리에 없었습니다. 이것은 디렉토리입니다 프로젝트 파일 위치. 거기에서 옮겼으며 Vs.net에서 디버깅 할 때 작동합니다.

도움이 되었습니까?

해결책

열기 모드를 지정할 때 비트 또는 연산자를 사용해보십시오.

infile.open ("input.txt", ios::ate | ios::in);

그만큼 OpenMode 매개 변수는 비트 마스크입니다. ios::ate 추가를 위해 파일을 여는 데 사용되며 ios::in 입력을 읽기 위해 파일을 여는 데 사용됩니다.

파일 만 읽으려면 사용할 수 있습니다.

infile.open ("input.txt", ios::in);

IFStream의 기본 열기 모드는 iOS :: in이므로 이제이를 모두 제거 할 수 있습니다. 다음 코드는 G ++를 사용하여 작동합니다.

#include <iostream>
#include <fstream>
#include <cstdio>

using namespace std;

int main(int argc, char** argv) {
    ifstream infile;
    infile.open ("input.txt");

    if (infile)
    {
        while (infile.good())
            cout << (char) infile.get();
    }
    else
    {
        cout << "Unable to open file.";
    }
    infile.close();
    getchar();
    return 0;
}

다른 팁

때때로 Visual Studio는 EXE 파일을 소스 코드에서 멀리 떨어 뜨립니다. 기본적으로 vs는 EXE 파일에서 시작하는 파일 만 찾을 수 있습니다. 이 프로세스는 소스 코드와 동일한 디렉토리에서 입력 TXT 파일을 가져 오는 간단한 단계입니다. IDE 설정을 수정하고 싶지 않은 경우.

using namespace std;

ifstream infile;

string path = __FILE__; //gets source code path, include file name
path = path.substr(0,1+path.find_last_of('\\')); //removes file name
path+= "input.txt"; //adds input file to path

infile.open(path);

바라건대 이것은 다른 사람들이 빠른 해결책을 세우는 데 도움이됩니다. 이 설정을 직접 찾는 데 시간이 걸렸습니다.

코드에서 두 가지 문제를 발견했습니다.

a) "ios :: ate || ios :: in"=>의 구문 오류 "ios :: ate | ios :: in"

b) "ios :: ate"는 커서를 파일 끝으로 설정합니다. 그래서 읽기를 시작할 때 아무것도 얻지 못합니다.

그러니 "ios :: ate"를 제거하면 괜찮습니다. :)

Ciao, Chris

infile.open ("input.txt", ios::ate || ios::in);

|| Lizzard가 말한대로 BITWISE 연산자가 아니라 논리 또는 연산자입니다.

그래서 나는 당신이 다음과 동등한 일을하고 있다고 생각합니다.

infile.open ("input.txt", true);

(iOS :: ate 또는 iOS :: in은 0)

사용해보십시오 :

ifstream fStm("input.txt", ios::ate | ios::in);

또한 디버깅에 문제가 있습니다. "infile.good ()"또는 "infile.is_open ()"에서 시계를 설정할 수 없어야합니까? "오류 : 멤버 기능이 없음"을 계속받습니다.

그리고 적절한 내용은 다음을 포함합니다.

#include <fstream> 

등.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top