gpt4 book ai didi

C++将解析器的结果放入数组

转载 作者:行者123 更新时间:2023-11-27 23:40:58 25 4
gpt4 key购买 nike

我是 C++ 新手。

我想知道如何解析字符串并将结果放入数组中。

所以,假设我有一个这样的字符串:104.8 10.9 7.8e-33 2.6e-29 59 248 .. 46 230 .. 20 336 .. 0.87

它总是相同的阶梯,这意味着,14 个非 [:space:] 之间由可变数量的空格分隔。

我想使用正则表达式进行解析并将这些值放入一个数组中。因为我们知道有多少匹配,我们可以将数组长度设置为 14 char array[14];

在此先感谢您的帮助。

最佳答案

假设此数据已包含在 std::string 中,我会提出一个使用 std::stringstream 的解决方案,特别是 std::istringstream

我可以看到您同时拥有实数(104.87.8e-33)和字符串(..),其中,我假设,您也算作单独且有效的 token 。在这种情况下,我们可以将您的数据分成单独的 std::strings:

#include <iostream>
#include <sstream> // std::stringstream family
#include <array>
#include <string>

int main() {
std::string data{"104.8 10.9 7.8e-33 2.6e-29 59" // string concatenation
"248 .. 46 230 .. 20 336 .. 0.87"};

std::istringstream stream{data}; // helper stream

// Assuming that we're certain that *data* holds exactly 14 tokens, we can
// use a simple loop. Otherwise we would've needed to check stream's state
// after every operation.

std::array<std::string, 14> tokens{};

for(std::size_t i{0}; i < 14; ++i) {
stream >> tokens[i];
}

// lastly, we can print the results:

for(const auto& token : tokens) {
std::cout << token << ' ';
}
}

这将打印:104.8 10.9 7.8e-33 2.6e-29 59248 .. 46 230 .. 20 336 .. 0.87

请注意标记之间的额外空格消失了。

关于C++将解析器的结果放入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54787642/

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