所以我正在尝试创建一个 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++;
}
这行不通,有谁知道无需手动循环遍历字符串的方法吗?
最佳答案
使用 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]
带有必需的空终止符。
关于c++ - 将 std::string 放入 char[][] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9236084/