gpt4 book ai didi

C++ 格式化输入 : how to 'skip' tokens?

转载 作者:IT老高 更新时间:2023-10-28 21:52:04 26 4
gpt4 key购买 nike

假设我有一个这种格式的输入文件:

VAL1 VAL2 VAL3
VAL1 VAL2 VAL3

我正在编写一个只对 VAL1 和 VAL3 感兴趣的程序。在 C 中,如果我想“跳过”第二个值,我会这样做:

char VAL1[LENGTH]; char VAL3[LENGTH];
FILE * input_file;
fscanf(input_file, "%s %*s %s", VAL1, VAL3);

意思是,我会使用 "%*s"格式化程序让 fscanf() 读取这个标记并跳过它。 我如何使用 C++ 的 cin 来做到这一点? 有没有类似的命令?还是我必须读取一个虚拟变量?

提前致谢。

最佳答案

C++ String Toolkit Library (StrTk)对您的问题有以下解决方案:

#include <string>
#include <deque>
#include "strtk.hpp"

int main()
{
struct line_type
{
std::string val1;
std::string val3;
};

std::deque<line_type> line_list;

const std::string file_name = "data.txt";

strtk::for_each_line(file_name,
[&line_list](const std::string& line)
{
strtk::ignore_token ignore;
line_type temp_line;
const bool result = strtk::parse(line,
" ",
temp_line.val1,
ignore,
temp_line.val3);
if (!result) return;
line_list.push_back(temp_line);
});

return 0;
}

更多示例请见 Here

关于C++ 格式化输入 : how to 'skip' tokens?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/983460/

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