简体   繁体   English

C ++->>运算符如何工作?

[英]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();  
}

By default the operator>> in ifstream ignores the whitespaces. 默认情况下, ifstream中运算符>>会忽略空格。 If you want the whitespaces to be included, you have to use the std::noskipws manipulator flag as shown in the official documentation here . 如果你想被列入空格,您必须使用的std :: noskipws操纵标志所示的官方文档中的位置

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 with str.erase() , then reads characters from is and appends them to str as if by str.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() if is.width() > 0 , otherwise N is str.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 character c in is (this whitespace character remains in the input stream). std::isspace(c,is.getloc())是用于下一个字符真实cis (此空白字符保持在输入流中)。

If no characters are extracted then std::ios::failbit is set on is , which may throw std::ios_base::failure . 如果没有提取到字符,那么std::ios::failbit设置上is ,这可能会引发std::ios_base::failure

Finally, calls os.width(0) to cancel the effects of std::setw , if any. 最后,调用os.width(0)取消std::setw的影响(如果有)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM