2014-11-04 110 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