【问题标题】:c++ getline delimiter as any number?c ++ getline分隔符作为任何数字?
【发布时间】:2017-03-02 19:10:26
【问题描述】:

我输入的格式如下: John Smith 2,2 3,1 2,2 我需要将“John Smith”保存为一个字符串,然后将后续数字保存为一个向量。问题是,字符串部分可以是任意数量的单词。

我的计划是使用 getLine 并将分隔符设置为“任意数字”。这可能吗?我用谷歌搜索但找不到任何东西。谢谢。

【问题讨论】:

  • 不,分隔符是一个普通字符。这是个坏主意。
  • 读入字符串并搜索第一个数字。
  • 好的。这是个好主意。谢谢你。另外,我问这个问题的方式有问题吗?我似乎被否决了。会不会有不同的措辞?如果我弄错了,我很抱歉。

标签: c++ input delimiter getline istream


【解决方案1】:

试试这样的:

#include <string>
#include <sstream>
#include <vector>
#include <cctype>
#include <locale>
#include <iterator>
#include <algorithm>
#include <functional>

struct my_punct : std::numpunct<char> {
protected:
    virtual char do_decimal_point() const { return ','; }
    virtual std::string do_grouping() const { return "\000"; } // groups of 0 (disable)
};

struct sName {
    std::string value;
};

static inline void rtrim(std::string &s) {
    s.erase(
        std::find_if(
            s.rbegin(), s.rend(),
            std::not1(std::ptr_fun<int, int>(std::isspace))
        ).base(),
        s.end()
    );
}

std::istream& operator>>(std::istream &in, sName &out)
{
    char ch, last = 0;
    std::ostringstream oss;

    std::istream::sentry s(in);
    if (s)
    {
        out.value.erase();

        do
        {
            ch = in.peek();
            if (!in) break;
            if (std::isspace(last) && std::isdigit(ch)) break;
            ch = in.get();
            oss << ch;
            last = ch;
        }
        while (true);

        out.value = oss.str();
        rtrim(out.value);
    }

    return in;
}

std::string input = ...; // "John Smith 2,2 3,1 2,2"

sName name;
std::vector<double> v;

std::istringstream iss(input);
iss >> name;
iss.imbue(std::locale(iss.getloc(), new my_punct));
std::copy(
    std::istream_iterator<double>(iss),
    std::istream_iterator<double>(),
    std::back_inserter(v)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2013-10-21
    • 2010-09-18
    相关资源
    最近更新 更多