c++ getline 分隔符为任意数字?

标签 c++ input delimiter getline istream

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

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

最佳答案

尝试这样的事情:

#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)
);

关于c++ getline 分隔符为任意数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40160278/

相关文章:

sql - SSIS - 文本限定符目的

java - 输入数字时分隔文本字段中的数字 (Javafx)

python - Windows 7 cmd,来自 Visual Studio,不显示 float

c++ - getch() 和 scanf() 函数之间的区别

c - strcmp 在使用 fgets 读取的行上

Perl:一次读取一个字节的二进制文件

c++ - 尝试使用 OpenGL 设置 Xcode

c++ - 如何在不使用Qt Quick的情况下在qt桌面应用程序中实现qt虚拟键盘

css - 我如何按类定位输入按钮

java - 从文本文件中分割单词