2014-11-04 108 views
-2

我在顯示此文件時出現問題。我正在嘗試創建一個文件並將其顯示在輸出屏幕中。但getline不起作用。它不斷給我一個「40號線未聲明」的提示。我嘗試了一些事情,沒有做任何事情。問題是什麼?閱讀和顯示文件

#include <iostream> 

#include <fstream> 

#include <stdlib.h> 

#include <string> 


using namespace std; 

int main() 

{ 

    char filename[] = "Hello.txt"; 

    string line = "Hello, this is my output file"; 

    ofstream OutFile; 

    OutFile.open(filename); 

    if(OutFile.fail()) // check for successfully open , 

    { 

    cout << "file named can not be found \n"; 

    exit(1); 

    } 

    OutFile << line; 

    if (OutFile.is_open()) 

     OutFile.getline(line); 

    OutFile.close(); 

    system("pause"); 

} 
+0

我已經試過,它不起作用,或者 – jon 2014-11-04 22:12:38

+0

「不工作」是非常含糊。你得到了什麼錯誤? – 0x499602D2 2014-11-04 22:13:00

回答

0

std::getline()是一個免費的功能,而不是一個成員函數。成員函數版本用於原始字符數組,因爲您使用的是std::string,所以免費函數是適當的。

std::getline(Outfile, line); 

還要注意的是std::getline()只有std::istream類型的對象的工作,因爲你要嘗試執行輸入Outfile的對象不應該是std::ofstream 請將其改爲輸入文件流 std::ifstream

Outfile更改爲std::fstream這是一個雙向文件流。

+0

我將它改爲fstream並將getline用作「getline(Outfile,line);」並且它仍然不起作用。它說「OutFile undeclared」 – jon 2014-11-04 22:20:11

+0

@jon什麼是* exact *錯誤? – 0x499602D2 2014-11-04 22:22:09

+0

36 C:\ Users \ s346lab \ Documents \ Untitled1.cpp'Outfile'未聲明(首先使用此功能) – jon 2014-11-04 22:23:18