【问题标题】:Explanation of >> operator in C++C++中>>运算符的解释
【发布时间】:2014-12-13 21:41:48
【问题描述】:

我编辑了一段代码,旨在从 .txt 文件中读取整数并使用 cout 显示它们。它旨在显示第一个整数,后跟一个逗号,然后是运行总平均值,当 .txt 中有空行或 singke 整数时,出现问题。有人建议我将代码更改为:

  using namespace std;
  # include <iostream>
  #include <fstream>
  #include<string>

int main ()
{
double y = 0,x = 0,value1 =0;
string myFileName,myString;
cout<< "please enter the name of the file you wish to open"<<"\n";
cin>>myFileName;

ifstream inFile;
inFile.open(myFileName.c_str());

while (!inFile.eof())
{
    double currentAv;

    //while(getline(inFile,myString,(' ')))
    while(inFile>>value1)
    {


        y=y+1;
        //value1 = atof(myString.c_str());
        currentAv=(value1+x)/y;
        cout<<value1<<","<<currentAv<<endl;
        x=value1+x;
    }

}





inFile.close();
system("pause");
}

去掉//的2行,while循环改成:

while(inFile>>value1)

问题是我需要了解新代码与旧代码的不同之处。有人可以帮忙吗?我知道它会移位,但我不明白为什么会这样。代码确实有效。

【问题讨论】:

  • 不是位移,是istream operator
  • 它从您的ifstream 读取(这就是您在上面几行打开文件的原因),然后从该流读取到您的value1 变量。
  • 我真的不明白我是一个 c++ 菜鸟 :(
  • 你真的应该看看阅读introductory C++ book。这应该在很早的时候介绍。
  • 我不明白为什么循环工作

标签: c++ operators


【解决方案1】:

让我们一步一步来看看发生了什么。

inFile>>value1

这会调用istream::operator>>,它从流中读取double 并返回对流对象的引用,即inFile 本身。

while(inFile>>value1)

while 语句的条件必须可转换为bool。现在我们知道inFile&gt;&gt;value1 的类型是std::istream&amp;,并且确实存在istream::operator bool,如果没有设置错误标志(这意味着最后一次读取操作不成功),则返回true

所以,while(inFile&gt;&gt;value1) 的整体含义是:在你能做到的时候从inFile 中读取value1

以及与getline 加上atof 相比的差异。首先,&gt;&gt; 一直读取到任何空白字符,而不仅仅是代码中的空格。其次,它会因无效输入而失败。第三,它只是更地道。

【讨论】:

    猜你喜欢
    • 2014-05-06
    • 2015-06-17
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2019-07-07
    • 2013-01-01
    相关资源
    最近更新 更多