在C ++中以正斜杠分隔输入 [英] Separating input on forward slash in C++

查看:85
本文介绍了在C ++中以正斜杠分隔输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我在开始之前说我对C ++真的很陌生.

Let me preface this by saying I am really new to C++.

我想从以A/B形式(在命令行中)输入的分数中获取分子和分母;将A和B放入各自变量的最简单方法是什么?

I want to grab the numerator and denominator from a fraction that gets entered in the form of A/B (in the command line); what is the easiest way to get A and B into their respective variables?

推荐答案

使用C ++的最简单方法是

The easiest approach using C++ is

double numerator, denominator;
char   dummy;
if (in >> numerator >> dummy >> denominator) {
    // ...
}

以上内容从流中读取有理值.要从命令行中的参数获取流,可以使用 std :: istringstream :

The above reads the rational value from a stream. To get a stream from an argument on the command line, you'd use an std::istringstream:

int main(int ac, char* av[]) {
    for (int i(1); i != ac; ++i) {
        std::istringstream in(av[i]);
        // ...
    }
}

主要缺点是,使用上述提取代码,分隔符可以是任何字符.要解决此问题,我将使用斜杠操纵器:

The main drawback is that the separating character can be anything with the extraction code mentioned above. To fix this up I'd use a slash manipulator:

std::istream& slash(std::istream& in) {
    if (in.get() != '/') {
        in.setstate(std::ios_base::failbit);
    }
    return in;
}
// ...
if (in >> numerator >> slash >> denominator) {
    // ...
}

由于该解决方案似乎值得赞赏,因此我想指出,根据需要,您可能需要略微调整 slash()的实现:发布的版本希望在分子后面有斜杠.跳过前导空格可能是合理的:

Since this solution seems to be appreciated, I want to point out that depending on needs you might want to slightly tweak the implementation of slash(): The posted version expects the slash right after the numerator. It may be reasonable to skip leading whitespace:

if ((in >> std::ws).get() != '/') {
    ...
}

此外,这是仅针对一个字符的一种特殊实现,您可能希望为其他字符使用类似的操纵器.为了避免复制代码,操纵器可以成为模板:

Also, this is a special implementation for just one character and you might want to have similar manipulators for other characters. To avoid replicating code the manipulator can become a template:

template <char Separator>
std::istream& separator(std::istream& in) {
    if ((in >> std::ws).get() != std::char_traits<char>::to_int_type(Separator) {
        // ...
}
typedef std::istream& (*separator_manipulator)(std::istream&);
separator_manipulator const slash = &separator<'/'>;
separator_manipulator const comma = &separator<','>;
// ...

使用 std :: char_traits< char> :: to_int_type()的需要是为了避免在使用带有负值的 char 时出现问题.

The need to use std::char_traits<char>::to_int_type() is there to avoid problems when using chars with a negative value.

这篇关于在C ++中以正斜杠分隔输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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