我有一个包含键和值的文本文件,如下所示:
keyOne=1
keyTwo=734
keyThree=22.3
keyFour=5
键只是小写和大写字母,就像我的例子一样。这些值是整数或浮点数。每个键和值由等号 (=) 分隔。现在我想将这些值读入我程序中的变量中。
这是我尝试读取值的代码:(我省略了将值存储在程序变量中的部分,现在将它们打印出来以进行演示。)
std::fstream file(optionsFile, std::fstream::in);
if (file.good()) {
int begin;
int end;
std::string line;
while(std::getline(file, line)) {
// find the position of the value in the line
for (unsigned int i = 0; i < line.length(); i++) {
if (line.at(i) == '=') {
begin = i + 1;
end = line.length();
break;
}
}
// build the string... it starts at <begin> and ends at <end>
const char *string = "";
for (int i = begin; i < end; i++) {
string += line.at(i);
}
// only gibberish is printed in the following line :(
std::cout << "string=" << string << std::endl;
}
}
我不明白为什么它不会打印值..而是只打印奇怪的东西甚至什么都没有
请帮助这让我的精神如此沉重:(