从TextFile读取数据,并在控制台中显示

read data from textfile and display in console

本文关键字:控制台 显示 TextFile 读取 数据      更新时间:2023-10-16

我想从以下文本文件中读取数据
路径C:folder1folder2example.txt
但是我的代码不起作用。我正在收到消息"无法打开文件",但文本文件存在。任何更正都将不胜感激。

#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;
}

我刚刚尝试过它,它可以完美