第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

將整個(gè)ASCII文件讀入C+std:string

將整個(gè)ASCII文件讀入C+std:string

C++ C
長(zhǎng)風(fēng)秋雁 2019-06-04 17:18:42
將整個(gè)ASCII文件讀入C+std:string我需要將整個(gè)文件讀入內(nèi)存,并將其放入C+中。std::string.如果我把它讀成char[]答案很簡(jiǎn)單:std::ifstream t;int length;t.open("file.txt");      // open input filet.seekg(0, std::ios::end);    // go to the endlength = t.tellg();           // report location (this is the length)t.seekg(0, std::ios::beg);    // go back to the beginningbuffer = new char[length];    // allocate memory for a buffer of appropriate dimensiont.read(buffer, length);       // read the whole file into the buffert.close();                    // close file handle// ... Do stuff with buffer here ...現(xiàn)在,我想做同樣的事情,但是使用std::string而不是char[]..我想避免循環(huán),也就是說,我別想:std::ifstream t;t.open("file.txt");std::string buffer;std::string line;while(t){std::getline(t, line);// ... Append line to buffer and go on}t.close()有什么想法嗎?
查看完整描述

3 回答

?
三國(guó)紛爭(zhēng)

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊

有幾種可能性。我喜歡用字符串作為中間的一種:

std::ifstream t("file.txt");std::stringstream buffer;buffer << t.rdbuf();

現(xiàn)在,“file.txt”的內(nèi)容在字符串中可用,如buffer.str().

另一種可能性(雖然我也不喜歡)更像是你的原作:

std::ifstream t("file.txt");t.seekg(0, std::ios::end);size_t size = t.tellg();std::string buffer(size, ' ');t.seekg(0);t.read(&buffer[0], size);

在官方上,這不需要在C+98或03標(biāo)準(zhǔn)下工作(字符串不需要連續(xù)存儲(chǔ)數(shù)據(jù)),但實(shí)際上它可以與所有已知的實(shí)現(xiàn)一起工作,而且C+11和更高版本確實(shí)需要連續(xù)存儲(chǔ),因此可以保證與它們一起工作。

至于為什么我也不喜歡后者:第一,因?yàn)樗L(zhǎng),更難讀。第二,因?yàn)樗竽媚魂P(guān)心的數(shù)據(jù)初始化字符串的內(nèi)容,然后立即對(duì)該數(shù)據(jù)進(jìn)行寫入(是的,與讀取相比,初始化的時(shí)間通常是微不足道的,所以這可能并不重要,但對(duì)我來說,這仍然是錯(cuò)誤的)。第三,在文本文件中,X在文件中的位置不一定意味著你必須讀取X字符才能達(dá)到這個(gè)值-它不需要考慮像行尾翻譯之類的內(nèi)容。在執(zhí)行此類轉(zhuǎn)換(例如,Windows)的實(shí)際系統(tǒng)中,翻譯后的表單比文件中的內(nèi)容短(即文件中的“\r\n”在已翻譯的字符串中變?yōu)椤癨n”),因此您所做的只是保留了一些您從未使用過的額外空間。再說一遍,這并不是真正的大問題,但還是覺得有點(diǎn)不對(duì)勁。


查看完整回答
反對(duì) 回復(fù) 2019-06-04
?
慕蓋茨4494581

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊

我認(rèn)為最好的方法是使用字符串流。簡(jiǎn)單又快!

#include <fstream>#include <iostream>#include <sstream> //std::stringstreammain(){
    std::ifstream inFile;
    inFile.open("inFileName"); //open the input file

    std::stringstream strStream;
    strStream << inFile.rdbuf(); //read the file
    std::string str = strStream.str(); //str holds the content of the file

    std::cout << str << std::endl; //you can do anything with the string!!!}


查看完整回答
反對(duì) 回復(fù) 2019-06-04
  • 3 回答
  • 0 關(guān)注
  • 716 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)