[英]Why cin accepts string inputs after including String header
I am new to C++ programming. 我是C ++编程的新手。 I was trying to take user inputs and put them in a variable and i was using
cin
. 我试图接受用户输入并将其输入变量中,而我正在使用
cin
。 It was working for integer's and other's except strings
. 它适用于integer和other的其他
strings
。 So, when I searched around I found that I have to include <string>
header. 因此,当我四处搜索时,我发现必须包含
<string>
标头。 I just want to understand, what changes occurred by including string header? 我只想了解,包含字符串标题会发生什么变化? I thought that
cin
is overloaded by a function defined in the string header. 我以为
cin
被字符串标头中定义的函数重载了。 So, I started looking into string header and I could not find cin
overloaded or any function defined there at all. 因此,我开始研究字符串标题,却找不到
cin
重载或在那里定义的任何函数。 Can any one tell me how cin
started accepting string inputs after including <string>
? 谁能告诉我
cin
在包含<string>
之后如何开始接受字符串输入?
<string>
defines the functions <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);
These free, standard library functions, are what allows you to use a std::string
with any stream that is or is derived from a basic_ostream
or basic_istream
. 这些免费的标准库函数使您可以将
std::string
与basic_ostream
或basic_istream
basic_ostream
任何流basic_istream
。
The <string>
header mainly defines the standard library's std::string
class. <string>
标头主要定义标准库的std::string
类。 Without it, you have no string class in C++: It's not integral to the language. 没有它,您在C ++中就没有字符串类:它不是该语言不可或缺的。 Of course you could use
char*
-strings, C-style, but that's not how we typically do things in C++. 当然,您可以使用
char*
-strings,C风格,但这不是我们通常在C ++中执行的方式。
Along with std::string
, that header also defines >>
and <<
operators for std::string
's and streams, so that you can do things like std::cout << my_string
and std::cin >> another_string
. 除了
std::string
,该标头还为std::string
和流定义了>>
和<<
运算符,以便您可以执行std::cout << my_string
和std::cin >> another_string
。 That syntax is equivalent to operator<<(std::cout, my_string)
and operator>>(std::cin, another_string)
. 该语法等效于
operator<<(std::cout, my_string)
和operator>>(std::cin, another_string)
。
Important note: The C language's <string.h>
header is completely different than C++'s <string>
. 重要说明:C语言的
<string.h>
标头与C ++的<string>
完全不同。 The C language header is usable just like it is in C, and defines certain functions working on char*
(null-terminated) strings . C语言标头就像在C语言中一样是可用的,并且定义了某些对
char*
(以null终止)的字符串起作用的函数 。 Don't confuse the two headers, nor the two kinds of "strings". 不要混淆两个标题,也不要混淆两种“字符串”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.