2010-05-17 44 views
0

好的我有這個程序使用C字符串工作。我想知道是否有可能讀取未格式化的文本塊到std :: string?我用if >>玩弄了周圍的東西,但是這樣一行一行地讀。我一直在打破我的代碼,並試圖使用std :: string將我的頭靠在牆上,所以我認爲是時候邀請專家了。這裏有一個工作程序,你需要提供一個帶有一些內容的文件「a.txt」以使其運行。未格式化的輸入到一個std ::字符串,而不是二進制文件中的c字符串

我試圖愚弄周圍:

in.read (const_cast<char *>(memblock.c_str()), read_size); 

,但行事古怪。我必須做std::cout << memblock.c_str()才能打印出來。和memblock.clear()沒有清除字符串。

無論如何,如果你能想到一種使用STL的方式,我將不勝感激。

下面是使用C字符串

// What this program does now: copies a file to a new location byte by byte 
// What this program is going to do: get small blocks of a file and encrypt them 
#include <fstream> 
#include <iostream> 
#include <string> 

int main (int argc, char * argv[]) 
{ 
int read_size = 16; 
int infile_size; 
std::ifstream in; 
std::ofstream out; 
char * memblock; 
int completed = 0; 

memblock = new char [read_size]; 
in.open ("a.txt", std::ios::in | std::ios::binary | std::ios::ate); 
if (in.is_open()) 
    infile_size = in.tellg(); 
out.open("b.txt", std::ios::out | std::ios::trunc | std::ios::binary); 

in.seekg (0, std::ios::beg);// get to beginning of file 

while(!in.eof()) 
{ 
    completed = completed + read_size; 
    if(completed < infile_size) 
    { 
    in.read (memblock, read_size); 
    out.write (memblock, read_size); 
    } // end if 
    else // last run 
    { 
    delete[] memblock; 
    memblock = new char [infile_size % read_size]; 
    in.read (memblock, infile_size % read_size + 1); 
    out.write (memblock, infile_size % read_size); 
    } // end else 
} // end while 
} // main 

,如果你看到任何可能使該代碼更好的請隨時讓我知道我的計劃。

+0

我真的不明白你用'std :: string'的問題:你是說你必須調用'c_str()'來打印內容並且clear()沒有清除字符串? – 2010-05-17 03:12:16

回答

4

而不是使用std::string,請考慮使用std::vector<char>;這可以讓你解決調用std::string::c_str()時產生的const_cast的所有問題。在開始使用之前,只需調整矢量大小即可。

如果你要打印的內容,你可以通過按一個空終止到回空字符結束的向量的內容:

std::vector<char> v; 
v.push_back('\0'); 
std::cout << &v[0]; 

,或者你可以將其轉換成std::string

std::vector<char> v; 
std::string s(v.begin(), v.end()); 

這一切都假設您有一些要從二進制文件中讀取的文本塊。如果您試圖打印出二進制字符,這顯然不起作用。你的問題並不完全清楚。

+1

爲什麼不直接在這裏使用字符串? '&myString [0]' – 2010-05-17 04:25:02

+0

@比利:嗯。這是一個好主意;我想我從來沒有想到這一點。 ':-P'無論好壞,我想我已經阻止了任何依賴於'std :: string'的元素被連續存儲的東西,因爲這個主題已經討論了很多。 – 2010-05-17 14:00:48