从文本文件中读取数据并显示在控制台中

read data from textfile and display in console

我想从下面存储的文本文件中读取数据
路径 C:\folder1\folder2\example.txt
但我的代码不工作。我收到消息 "Unable to open file" 但文本文件 exists.Any 更正将不胜感激。

#include <windows.h>
#include <fstream>
#include <string>
#include <iostream>


using namespace std;

int main()
{
string filename, line;
SetCurrentDirectoryA( "C:\folder1\folder2\" );

ifstream inFile;
inFile.open("example.txt");
if (!inFile) {
    cout << "Unable to open file";
    exit(1); // terminate with error
}

while (inFile >> line) {
    cout << line << endl ;
}

inFile.close();
return 0;
}
#include <iostream>
#include <fstream>

int main()
{
    char buf[256];
    std::ifstream inFile("C:\folder1\folder2\example.txt");
    if (!inFile.is_open()) {
        std::cout << "Unable to open file";
        exit(1); // terminate with error
    }
    while (inFile >> buf) {
        std::cout << buf << std::endl;
    }

    inFile.close();
    return 0;
}

我刚刚试过了,效果很好