从字符串加载变量

Load variable from string

本文关键字:变量 加载 字符串      更新时间:2023-10-16

我应该如何从字符串加载变量?例如,这是我的文本文件:

国际: 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