2016-05-16 103 views
-1

失敗我目前使用的Visual Studio 2015年閱讀文件在C++中

#include "stdafx.h" 
#include "fstream" 
#include "iostream" 
using namespace std; 

int main() { 
    ifstream infile; 
    infile.open("hello.txt"); 

    if (infile.fail()) { 
     cerr << "error to open"; 
     exit(1); 
    } 

    int x, y; 
    infile >> x >> y; 
    cout << x << y << endl; 

    return 0; 
} 
  1. 我包括資源文件夾中的文件hello.txt的。

它仍然沒有從文件中讀取它。

我不確定它的視覺工作室或其他東西的設置問題。

+0

難道你是單獨運行程序還是使用附加的調試器? (在Visual Studio中運行) –

+0

你是什麼意思「仍然沒有從文件中讀取它」? – Carcigenicate

+0

添加一些臨時代碼,用於寫入文件以打開文件。查看文件的創建位置,然後將輸入文件放在同一目錄中。 –

回答

0

你要打開的文件並不在當前目錄(因爲「hello.txt的」是相對路徑),試試這個代碼:

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

#include <windows.h> 

using namespace std; 

std::string MakeAbsolutePath(const std::string& file) { 
    static const DWORD buff_size = 512; 
    char buff[buff_size] = { 0 }; 
    // TODO: error handling,see GetCurrentDirectory Function 
    DWORD has_writen = ::GetCurrentDirectoryA(buff_size, buff); 

    return std::string(buff) +"\\"+ file; 
} 

int main() 
{ 
    ifstream infile; 

    std::string file_path = MakeAbsolutePath("hello.txt"); 
    cout << "going to open file :"<< file_path << endl; 
    infile.open(file_path); 

    if (infile.fail()) { 
     cerr << "error to open"; 
     exit(1); 
    } 

    int x, y; 
    infile >> x >> y; 
    cout << x << y << endl; 


    return 0; 
} 

運行它,並檢查控制檯輸出