我有一个数据文件,其中包含用=字符分隔的键值对。
示例数据文件如下所示。
A = 1
B = 2
C = 3
D = 4我只想从数据文件中读取一些密钥。例如,在本例中,我只想读取A和C键。我使用了for循环和getline来完成此操作,但无法获取数据。
下面是MWE。
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
// pretend file stream
std::istringstream data(R"(
A = 0.0000
B = 1.0000
C = 2.0000
D = 3.0000
)");
int main()
{
double A, C;
for(std::string key; std::getline(data, key, '='); ){
std::cout << key << "Printed Key." << std::endl;
if(key == "A "){
data >> A;
std::cout << A << std::endl;
}
else if(key == "C "){
data >> C;
std::cout << C << std::endl;
}
}
}由于某些原因,当我打印密钥时,它给出了以下输出。而不是从它停止的地方开始阅读。
A Printed Key.
0.0000
B Printed Key.
1.0000
C Printed Key.
2.0000
D Printed Key.
3.0000
Printed Key.发布于 2020-10-12 20:40:54
从第二个getline()开始,key值将是上一个调用的行中剩余的值,直到下一行中的下一个=。这个例子将使它更容易理解。
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
// pretend file stream
std::istringstream data("A = 0.0000\n"
"B = 1.0000\n"
"C = 2.0000\n"
"D = 3.0000\n");
int main()
{
double A, C;
for(std::string key; std::getline(data, key, '='); ){
std::cout << key << "Printed Key." << std::endl;
if(key == "A "){
data >> A;
std::cout << A << " A value printed" << std::endl;
}
else if(key == " 1.0000\nC "){
data >> C;
std::cout << C << " C value printed" << std::endl;
}
}
}您可以在每个循环的末尾添加另一个getline(),以获得该行的其余部分,这样代码就可以工作了
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
// pretend file stream
std::istringstream data("A = 0.0000\n"
"B = 1.0000\n"
"C = 2.0000\n"
"D = 3.0000\n");
int main()
{
double A, C;
for(std::string key; std::getline(data, key, '='); ){
std::cout << key << "Printed Key." << std::endl;
if(key == "A "){
data >> A;
std::cout << A << " A value printed" << std::endl;
}
else if(key == "C "){
data >> C;
std::cout << C << " C value printed" << std::endl;
}
std::getline(data, key);
}
}发布于 2020-10-12 20:43:38
这看起来像ini文件或其中的一部分。因此,与其重复发明轮子,不如使用像boost这样的现成解决方案。
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
int main()
{
using namespace boost::property_tree;
ptree values;
ini_parser::read_ini(std::cin, values);
std::cout << values.get<double>("A") << '\n';
std::cout << values.get<double>("B") << '\n';
std::cout << values.get<double>("C") << '\n';
std::cout << values.get<double>("D") << '\n';
return 0;
}https://stackoverflow.com/questions/64317582
复制相似问题