如何使用std::cin.getline()与string

how I can use std::cin.getline() with string

本文关键字:string cin 何使用 std getline      更新时间:2023-10-16

我有一个关于c++中的字符串的问题

我想从用户读取22个字符并将它们存储在字符串

我试着:

std::string name;
std::cin.getline(name,23);

显示错误。

使用cin的解决方案是什么?Getline with string ?

您使用<string>中的std::getline(std::istream&, std::string&)

如果你想把事情限制在22个字符,你可以使用std::string,就像你将它传递给任何c风格的API一样:

std::string example;
example.resize(22); // Ensure the string has 22 slots
stream.getline(&example[0], 22); // Pass a pointer to the string's first char
example.resize(stream.gcount()); // Shrink the string to the actual read size.

有两种不同的getline函数。一个是istream类的成员,大致如下:

std::istream &std::istream::getline(char *buffer, size_t buffer_size);

另一个是自由函数,像这样:

std::istream &std::getline(std::istream &, std::string &);

您想调用前者,但实际上需要后者。

虽然我不认为前者被正式弃用,但我怀疑大多数真正关注自己"游戏"的c++程序员会这样考虑——为了向后兼容,它可能无法被删除,但很有可能你永远不应该使用它。

这段代码读取22个字符并将它们放入一个字符串中。

char buf[22];
cin.read(buf, 22);
string str(buf, 22);

如果这是你真正想要的,那么这就是代码