ifstream 无法读取文件

ifstream unable to read file

我一直在尝试在 Visual Studio 2015 年制作一个控制台应用程序,它将文本文件读取为字符串,然后输出该字符串,但我遇到了一些问题。

我尝试的第一件事是遵循 cplusplus.com 教程:

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

using namespace std;

int main()
{
    string line;
    ifstream myfile("test.txt");
    if (myfile.is_open())
    {
        while (getline(myfile, line))
        {
            cout << line << '\n';
        }
        myfile.close();
    }

    else cout << "Unable to open file";
    return 0;
}

程序没有打开文件。

尽管进行了多次互联网搜索并尝试了 20 多种不同的方法,但我仍然无法让我的程序运行。我能达到的最好结果是一排毫无意义的 0。

我哪里错了?

您做错的是没有发出有用的错误消息。与其打印“无法打开文件”,不如让计算机告诉您无法打开文件的原因。例如:

#include <iostream>                                                                                
#include <fstream>                                                                                 
#include <string>                                                                                  
                                                                                                   
using namespace std;                                                                               
                                                                                                   
int main(int argc, char **argv)                                                                   
{                                                                                                  
    int rv = 0; 
    string line;                                                                                   
    const char * path = argc > 1 ? argv[1] : "test.txt";                                           
    ifstream myfile(path);                                                                         
    if( myfile.is_open() ){                                                                        
        myfile.close();                                                                            
    } else {                                                                                       
        perror(path);
        rv = 1;                                                                              
    }                                                                                              
    return rv;                                                                                      
}