【发布时间】: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。这应该在很早的时候介绍。
-
我不明白为什么循环工作