【问题标题】:c++ inputing a string - not with getline() but with cinc++ 输入字符串 - 不是用 getline() 而是用 cin
【发布时间】:2014-07-05 04:15:52
【问题描述】:

输入带空格的字符串!

这是我的想法:

string name;
std::cout << "Please enter your full name: ";
std::cin >> std::noskipws;
while (std::cin >> name >> std::ws) {
    full_name += name + " ";
}

说你的名字是 Bill Billy Bobby Bronson Billson。

或者像添加这样的东西:

if (name == "\n")
  break;

使用 getline(),这是一个语句。但是,出于研究原因,我不想使用 getline()。

可以吗?

更新:

如果我尝试我的代码,无论我更改什么,我都会得到一个无限循环。

【问题讨论】:

标签: c++ string iostream


【解决方案1】:

我不明白你为什么真的想这样做,但是是的,这是可能的。

operator&gt;&gt; for std::string 读取输入字符,直到遇到空白字符。流有一个 ctype facet,用于确定字符是否为空格。

在这种情况下,您需要一个\n分类为空白的ctype facet。

struct line_reader: std::ctype<char> {
    line_reader(): std::ctype<char>(get_table()) {}
    static std::ctype_base::mask const* get_table() {
        static std::vector<std::ctype_base::mask> 
            rc(table_size, std::ctype_base::mask());

        rc['\n'] = std::ctype_base::space;
        return &rc[0];
    }
};  

您将包含该 ctype facet 的语言环境实例灌输给您的输入文件:

int main() {
    std::vector<std::string> lines;

    // Tell the stream to use our facet, so only '\n' is treated as a space.
    std::cin.imbue(std::locale(std::locale(), new line_reader()));

    // to keep things at least a little interesting, we'll copy lines from input
    // to output if (and only if) they contain at least one space character:
    std::copy_if(std::istream_iterator<std::string>(std::cin),
        std::istream_iterator<std::string>(),
        std::ostream_iterator<std::string>(std::cout, "\n"),
        [](std::string const &s) {
            return s.find(' ') != std::string::npos;
    });
}

这里我使用了std::istream_iterator,它使用指定类型(在本例中为std::string)的提取运算符来读取数据。

【讨论】:

    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 2014-04-07
    • 2012-08-24
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多