c++ - 将 std::string 放入 char[][] 数组

标签 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++;
}

这行不通,有谁知道无需手动循环遍历字符串的方法吗?

最佳答案

使用 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/

相关文章:

c++ - 在匿名实例创建中使用先前变量时重新声明错误

c++ - 从 .cproject 转向 .vcproj

c++ - 检测公共(public)基类

PHP多行,连接字符串

c++ - 使用相同的临界区对象读写

c# - 多线程文件写入排队

c - 遇到文件 I/O 和字符串数组的问题

c++ - 为什么我不能从派生类中调用基类运算符?

不同 DLL 甚至线程之间的 C++ 安全字符串

python - 为什么乘法会重复数次?