c++函数返回整行Fstream

fstream c ++ functions return full line fstream

本文关键字:Fstream 返回 函数 c++      更新时间:2023-10-16

c++语言创建一个个人网页,这里我使用C++作为cgi输出到一个web服务器XAMP,加载fstreamc ++ html分离稿件,使htmlstream功能块在记事本中不太复杂的同时编码c ++,问题是当一个功能htmlstream制作时,只有一行文本,它不能显示所有的文本

#include <iostream>
#include <fstream>
using namespace std;
string htmlstream(const char* _filename){
    string htmltext;
    fstream open_html (_filename);
    if(open_html.is_open()){
            while(getline(open_html,htmltext)){
                    return htmltext;
            }
    }else{
    cout<<"File: NO Reading"<<endl;
    }
}
int main(){
    string importhtml = htmlstream("body.html");
    cout<<importhtml;
    return 0;
}

只显示一行文本的原因是因为函数getline读取直到它到达当前行的末尾。也就是说,每次读取一行时,字符串变量的值都会改变。如果您希望存储每行的值,则必须在读取时附加每行。有多种解决方案,我决定用一些简单的。

看看是否有帮助。

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
/// Simplify calls to the standard library
using namespace std;
string htmlStream( const char *fileName )
{
    string   text;      /// Content of current file
    ifstream inFile;    /// Input file stream
    inFile.open( fileName );  /// Open file to read
    if ( inFile.is_open() ) {
        /// File successfully open, so process it
        string line;  /// String being read
        /// Read file, line by line
        while ( getline( inFile, line ) ) {
            text += line;
        }
    }
    else {
        /// Could not open file, so report error to the stderr
        cerr << "Cannot open "" << fileName << """ << endl;
        exit( EXIT_FAILURE );
    }
    return text;
}
int main( int argc, const char * argv[] ) {
    string str = htmlStream( "darkness.txt" );
    cout << str << endl;
    return EXIT_SUCCESS;
}