c++不是用getline()而是用cin输入a

c++ inputing a not with getline() but with cin

本文关键字:cin 输入 getline c++      更新时间:2023-10-16

输入一个带空格的字符串!

我是这么想的:

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()。

可以做到吗?

更新:

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

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

operator>> (std::string)读取输入字符,直到遇到空白字符。流有一个ctype facet,用来确定一个字符是否为空白。

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

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)来读取数据。