将std :: string放入char [] []数组中

时间:2012-02-10 23:07:41

标签: c++ string file-io multidimensional-array

所以我试图创建一个Befunge interperter并将文本文件读入数组。 我正在使用此代码:

char map[100][100]; //not 85 x 20
//load the source
ifstream f;
f.open("file.txt", ios::in);
string s;
int i = 0;
while(f.good() && i < 100)
{
    getline(f, s);
    map[i] = s.c_str();
    i++;
}

这不起作用,有没有人知道如何在不手动循环字符串的情况下执行此操作?

3 个答案:

答案 0 :(得分:3)

使用strncpy()并指定字节数:

strncpy(map[i], s.c_str(), 100);
map[i][99] = '\0'; /* this could trim s.c_str(), but at least you don't get an overflow */

而不是:

map[i] = s.c_str();

通过指定最多复制为100的字节数,可确保不会溢出map[i]。如果strncpy()map[i]函数会将strlen(s.c_str()) < 100与终结符匹配。在strlen(s.c_str()) >= 100的情况下,字符串将被截断,以便为map[i]提供必需的null终止符。

答案 1 :(得分:0)

我认为这样做更安全

char* map[100];
....   

while(f.good() && i < 100)
{
    getline(f, s);
    map[i] = new char[s.length() + 1];
    strcpy (map[i], s.c_str());
    i++;
}

答案 2 :(得分:-1)

与此处发布的其他答案相反,您不应该尝试使用strcpy复制到“地图”中。 在进行任何复制之前,您需要确保不要超出缓冲区。为此,您不应使用源的大小,而应使用目标的大小。原因是源可能比目的地有空间更长。为了避免在你完成其他事情之前可能无法解决的问题 密集计算时,您应确保不要尝试复制到不足以包含要复制到其中的内容的目标。

这是复制字符串的函数签名(嗯,你应该在这里使用的那个):

strncpy(dest, source, size);

以下是您应该使用的内容:

strncpy(map[i], s.c_str(), sizeof(map[i]));

编辑:

或者您可以使用strncpy_s()(如果您使用的是Windows!),它允许您指定源和目标长度。

strncpy_s(dest, dest_size, source, source_size)