如何使用std::cin.getline()与string
how I can use std::cin.getline() with string
我有一个关于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);
如果这是你真正想要的,那么这就是代码
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- cppcheck在const std::string[]上引发警告
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 将std::string传递给WriteConsole API
- Problems with std::cin.fail()
- 为std::string的某个索引赋值
- std::string 是否仅适用于 c++ 中的'std::cin'
- std::getline(std::cin, string) 可能因键盘输入失败的方式
- 为什么我们需要在getline(cin,string)之前使用cin.ignore()
- 当使用getline(cin,string)时,CIN会自动获取其值而不询问
- C ++多个CIN默认值(如果未输入),则添加到map<string,vector<double>>
- 为什么像cin,cout,string等东西被认为是对象
- std::cin >> std::string 是如何实现的?
- Using cin AFTER getline(cin, string)
- 关于getline(cin,string)的C++快速问题
- getline(cin,string)与cin.ignore()一起不工作
- 输入Std::cin与直接赋值Std::string变量不一样
- How cin to string?
- 如何使用std::cin.getline()与string
- Compare string对cin不起作用