2016-05-16 101 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; 
} 

运行它,并检查控制台输出