2016-11-19 70 views
-2

我想存储线从阵列中的一个文件,这很容易用字符串做:C++:从字符串为char *

std :: string query[100]; 

std::ifstream ifs(filename); 

if (ifs.is_open()) 
{ 
    while (getline(ifs, query[size])) 
    { 
     size++; 
    } 
} 

问题是,我不能使用的字符串。我如何使这个工作,如果查询是一个char *数组?

+0

'问题是,我不能使用strings' - 没有什么会从创建阻止你一个简化的字符串类,并用它来代替。这就是你真正阻止这样的限制的原因。 – PaulMcKenzie

+1

[std :: string to char \ *]可能重复(http://stackoverflow.com/questions/7352099/stdstring-to-char) –

回答

1

一种简单的方法(但容量有限)是分配一些缓冲区并将数据读入其中。

const int maxLength = 1024; // specify enough length 
char* query[100]; 

std::ifstream ifs(filename); 

if (ifs.is_open()) 
{ 
    while (ifs.getline(query[size] = new char[maxLength], maxLength)) 
    { 
     size++; 
    } 
    delete[] query[size]; // delete buffer where data wasn't read 
} 

为了避免超出范围的访问,在while语句中的条件应该是

while (size < sizeof(query)/(*query) && // size is less than number of elements in query 
    ifs.getline(query[size] = new char[maxLength], maxLength))