2017-04-21 214 views
0

文本文件和显示数据我想从存储在以下
路径C:\folder1\folder2\example.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; 
} 
+4

你为什么不只是使用'inFile.open( “C:\\ \\文件夹1 \\文件夹2 example.txt的” );'? – NathanOliver

+0

@NathanOliver我尝试过,但没有奏效 – lorrainemutheu

回答

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

我只是试着它和它的作品完美