[英]C++ - How does the >> operator work?
I have a question regarding the >>
operator. 我对
>>
运算子有疑问。
I wrote a program to count number of words in a binary file. 我编写了一个程序来计算二进制文件中的单词数。
My question is about the while loop, shouldn't the >>
read the space, go into the loop, increment c, but just not put anything into w ? 我的问题是关于while循环,
>>
是否不应该读取空格,进入循环,递增c,但不要在w中放入任何内容?
It gives me an output of 4, but counting the spaces shouldn't it be 10? 它给我的输出是4,但算上空格应该不是10吗?
Any help is appreciated. 任何帮助表示赞赏。 My code is below:
我的代码如下:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
ofstream a;
ifstream b;
void main()
{
clrscr();
char w[20];
a.open("newf.txt",ios::binary);
a<<"This is an example\n";
a.close();
b.open("newf.txt");
int c=0;
while(b>>w)
{
c++ ;
}
cout<<c;
b.close();
getch();
}
First off, you're extracting into char w[20]
don't do this . 首先,您要提取到
char w[20]
请不要这样做 。 If a sting longer than 20 character is extracted bad things will happen. 如果提取的字符串超过20个字符,则会发生不良情况。 Instead use
string w
. 而是使用
string w
。
string::operator>>
is what is called by b >> w
which will: string::operator>>
是b >> w
所调用的,它将:
Behaves as a FormattedInputFunction.
表现为FormattedInputFunction。 After constructing and checking the sentry object, which may skip leading whitespace, first clears
str
withstr.erase()
, then reads characters fromis
and appends them tostr
as if bystr.append(1, c)
, until one of the following conditions becomes true:在构造并检查了可能跳过前导空格的哨兵对象之后,首先使用
str.erase()
清除str
,然后从is
读取字符并将它们附加到str
,就像通过str.append(1, c)
,直到其中一个满足以下条件:
- N characters are read, where N is
is.width()
ifis.width() > 0
, otherwise N isstr.max_size()
N个字符被读取,其中N是
is.width()
如果is.width() > 0
,否则N是str.max_size()
- the end-of-file condition occurs in the stream
is
文件结束条件发生在流中
is
std::isspace(c,is.getloc())
is true for the next characterc
inis
(this whitespace character remains in the input stream).std::isspace(c,is.getloc())
是用于下一个字符真实c
在is
(此空白字符保持在输入流中)。If no characters are extracted then
std::ios::failbit
is set onis
, which may throwstd::ios_base::failure
.如果没有提取到字符,那么
std::ios::failbit
设置上is
,这可能会引发std::ios_base::failure
。Finally, calls
os.width(0)
to cancel the effects ofstd::setw
, if any.最后,调用
os.width(0)
取消std::setw
的影响(如果有)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.