在C ++中读取格式化输入的最简单方法是什么? [英] The easiest way to read formatted input in C++?

查看:102
本文介绍了在C ++中读取格式化输入的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有任何方法读取这样的格式化字符串,例如:48754 + 7812 = Abcs

Is there any way to read a formatted string like this, for example :48754+7812=Abcs.

让我们假设我有三个stringz X,Y和Z,我想要

Let's say I have three stringz X,Y and Z, and I want

X = 48754 
Y = 7812
Z = Abcs

两个数字的大小和字符串的长度因此我不想使用 substring()或任何类似的东西。

The size of the two numbers and the length of the string may vary, so I dont want to use substring() or anything like that.

这样的参数

":#####..+####..=SSS.."

,因此它直接知道发生了什么事。

so it knows directly what's going on?

推荐答案

一种可能性是 boost :: split() ,它允许指定多个分隔符,并且不需要输入大小的先验知识:

A possibility is boost::split(), which allows the specification of multiple delimiters and does not require prior knowledge of the size of the input:

#include <iostream>
#include <vector>
#include <string>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>

int main()
{
    std::vector<std::string> tokens;
    std::string s(":48754+7812=Abcs");
    boost::split(tokens, s, boost::is_any_of(":+="));

    // "48754" == tokens[0]
    // "7812"  == tokens[1]
    // "Abcs"  == tokens[2]

    return 0;
}

或者,使用 sscanf()

Or, using sscanf():

#include <iostream>
#include <cstdio>

int main()
{
    const char* s = ":48754+7812=Abcs";
    int X, Y;
    char Z[100];

    if (3 == std::sscanf(s, ":%d+%d=%99s", &X, &Y, Z))
    {
        std::cout << "X=" << X << "\n";
        std::cout << "Y=" << Y << "\n";
        std::cout << "Z=" << Z << "\n";
    }

    return 0;
}

但是,这里的限制是字符串的最大长度c $ c> Z )必须在解析输入之前决定。

However, the limitiation here is that the maximum length of the string (Z) must be decided before parsing the input.

这篇关于在C ++中读取格式化输入的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆