C++ loadFromMemory 函数:从内存加载字符串到向量
C++ loadFromMemory 函数:从内存加载字符串到向量
以下是一个示例的 C++ 函数 loadFromMemory 的源代码,该函数将一个以 null 结尾的字符串从内存中加载到一个字符串向量中。
#include <iostream>
#include <string>
#include <vector>
void loadFromMemory(std::vector<std::string>& data, const char* memory) {
const char* ptr = memory;
std::string str;
while (*ptr != '\0') {
if (*ptr == '\n') {
data.push_back(str);
str.clear();
} else {
str += *ptr;
}
ptr++;
}
if (!str.empty()) {
data.push_back(str);
}
}
int main() {
std::vector<std::string> data;
const char* memory = "Hello\nWorld\nThis\nIs\nA\nTest\n";
loadFromMemory(data, memory);
for (const auto& str : data) {
std::cout << str << std::endl;
}
return 0;
}
这个函数的工作原理如下:
- 初始化一个指向内存地址的指针
ptr和一个空字符串str。 - 循环遍历内存中的每个字符,直到遇到 null 结尾符 ('\0')。
- 如果当前字符是换行符 ('\n'),则将当前字符串
str添加到向量data中,并清空str。 - 如果当前字符不是换行符,则将当前字符添加到
str中。 - 循环结束后,如果
str不为空,则将其添加到data中。
在 main 函数中,我们使用一个示例字符串来测试 loadFromMemory 函数,并将结果打印到控制台上。
这个函数可以用于从内存中加载各种数据,例如文本文件或网络数据。您可以根据自己的需要修改函数的逻辑来适应不同的数据格式。
原文地址: https://www.cveoy.top/t/topic/qr9Y 著作权归作者所有。请勿转载和采集!