-5 c++ arrays initialization const
我需要在C++ char数组中初始化非常量大小.大小必须是非常量的,因为它是从函数生成的,不能使用向量,因为这个char数组将用于读取和写入文件.例:
int i = functionToGetvalue();
unsigned char ch[i];
file1 >> ch;
file2 << ch;
Run Code Online (Sandbox Code Playgroud)
前提是错误的.虽然有理由选择c样式数组(或std::array)而不是向量,但你的肯定不是那个.您当然可以使用它std::vector来读取和写入文件,因为它保证在内存中是连续的.
例:
std::vector<char> vec;
vec.resize(255);
ssize_t sz = read(fd, vec.data(), vec.size());
Run Code Online (Sandbox Code Playgroud)
在您的原始示例中,您使用的是格式化流I/O,在这种情况下,std::string它是最好的工具:
std::string str;
file1 >> str; // reads up to the next white space into str
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |