gpt4 book ai didi

c++ - 如何读取=从文件中分离数据

转载 作者:行者123 更新时间:2023-12-02 09:58:01 25 4
gpt4 key购买 nike

我有一个数据文件,其中包含由 = 字符分隔的键值对。
示例数据文件如下所示。

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;
}
}

}
出于某种原因,当我打印 key 时,它会给出以下输出。而不是从它停止的地方开始阅读。
A Printed Key.
0.0000
B Printed Key.
1.0000
C Printed Key.
2.0000
D Printed Key.
3.0000
Printed Key.

最佳答案

从第二个getline()开始, key value 将是前一个调用的行中剩余的值,直到下一个 =在下一行。
这个例子会更容易理解。

#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);
}

}

关于c++ - 如何读取=从文件中分离数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64317582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com