从字符串加载变量
Load variable from string
我应该如何从字符串加载变量?例如,这是我的文本文件:
国际: 10
国际: 25
国际: 30
如何将这些加载到数组中? 这是我用来加载字符串的代码:
string loadedB[100];
ifstream loadfile;
loadfile.open("ints.txt");
if(!loadfile.is_open()){
MessageBoxA(0, "Could not open file!","Could not open file!", MB_OK);
return;
}
string line; int i = -1;
while(getline(loadfile, line)){ i++;
loadedB[i] = line;
}
loadfile.close();
for(int x = 0; x < count(loadedB); x++){
cout << loadedB[x] << endl;
}
我想做这样的事情:
int intarray[100];
loadfromstringarray(loadedB, intarray);
该代码将获取字符串的一部分(数字),并将该值放入数组中,如intarray[0] = 10;
等
编辑:istringstream是解决方案!
我个人喜欢旧的std::istringstream
对象:
const std::string example = "int: 10";
std::string prompt;
int value;
std::istringstream parse_stream(example);
std::getline(parse_stream, prompt, ':');
parse_stream >> value;
我个人喜欢老式的sscanf C函数:
int intarray[100];
int i = 0;
while(getline(loadfile, line) && i < sizeof(intarray)/sizeof(*intarray))
{
sscanf(line.c_str(), "int: %d", intarray + i++);
}
使用 stoi
:
vector<int> ints;
ifstream loadfile("ints.txt");
string line;
while(getline(loadfile, line)) {
ints.push_back(stoi(line.substr(5))); // skip the first 5 chars of each line
}
for(int i : ints) {
cout << i << endl;
}
输出:
10
25
30
相关文章:
- 视觉C++:在 DLL 加载期间,全局变量初始化顺序是否具有确定性?
- 使用动态加载库时静态变量为空
- C++:类如何将自身加载到内存中以递增全局变量?
- 使用共享指针加载到变量 C++ 中
- 我如何加载多个脚本而没有变量问题
- 托管语言是否锁定本机库的刷新和重新加载变量?
- 为什么主可执行文件和 dlopen 加载的共享库共享命名空间静态变量的一个副本?
- LLVM - 从具有偏移量的指针加载变量
- 是否可以在跨内核线程迁移后强制重新加载 thread_local 变量?
- 等待条件变量是否会加载 CPU 内核
- 加载 Lua 文件并使用变量而不执行函数
- 从字符串加载变量
- 从文件加载变量
- 在C++中从文本文件加载变量
- 将图像从URL加载到变量/ opencv Mat中
- 将游戏数据加载到没有全局变量的池中
- 将系统(char* 命令)的输出加载到变量 c++
- 如何防止编译器优化对从未使用的变量的加载
- 将内存中的8个字符作为打包的单精度浮点数加载到__m256变量中
- 共享库加载时静态变量损坏