为什么 cin 在包含字符串标头后接受字符串输入
Why cin accepts string inputs after including String header
我是C++编程新手。我试图获取用户输入并将它们放入变量中,我正在使用cin
. 它适用于整数和其他除strings
。因此,当我四处搜索时,我发现我必须包含<string>
标题。我只是想了解,包含字符串标头发生了哪些变化?我认为cin
被字符串标头中定义的函数重载了。因此,我开始研究字符串标头,但我找不到重载cin
根本没有定义任何函数。谁能告诉我cin
在包含字符串输入后是如何开始接受字符串输入<string>
的?
<string>
定义函数
template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str);
template <class CharT, class Traits, class Allocator>
std::basic_istream<CharT, Traits>&
operator>>(std::basic_istream<CharT, Traits>& is,
std::basic_string<CharT, Traits, Allocator>& str);
这些免费的标准库函数允许您将std::string
与任何流一起使用,该流是或派生自basic_ostream
或basic_istream
。
<string>
标头主要定义标准库的std::string
类。没有它,你就没有字符串类C++:它不是语言的组成部分。当然,你可以使用char*
字符串,C风格,但这不是我们通常在C++中做事的方式。
除了std::string
,该标头还为std::string
和流定义了>>
和<<
运算符,以便您可以执行诸如std::cout << my_string
和std::cin >> another_string
之类的操作。该语法等效于operator<<(std::cout, my_string)
和operator>>(std::cin, another_string)
。
重要说明:C 语言的<string.h>
标头与 C++ 的<string>
完全不同。C 语言标头就像在 C 中一样可用,并定义了处理char*
(以 null 结尾的(字符串的某些函数。不要混淆这两个标头,也不要混淆两种"字符串"。
相关文章:
- 如何使用堆栈将字符串输入拉伸 k 次
- 不确定出了什么问题(字符串输入)
- 如何获取字符串输入n次?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- isPalindrome不显示输出,isPalindrome函数未使用字符串输入作为字符串参数进行测试
- C++ 对象数组字符串输入在控制台上不起作用
- 为什么 cin 在包含字符串标头后接受字符串输入
- 拆分字符串输入并查找字符是否有效
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 将字符串输入到多维数组中
- 字符串输入后的空格
- 字符串流中的自定义字符串输入
- C 未验证字符串输入
- 总结数字字符串输入的最佳方法
- 如何验证用户将字符串输入到std :: cin中
- 在C++测试家庭作业问题中的字符串输入时无法退出循环(作为数据验证)
- 如何在C++中检测字符串输入中的换行符
- C++将字符串输入拆分为两个整数
- 如何检查字符串输入是否为有效的双精度
- 在读取数据文件时,如何找到用户字符串输入的字谜?