#include <iostream>
文件输入中的good()函数读取不到最后一个字符的问题
原创
©著作权归作者所有:来自51CTO博客作者blueyi的原创作品,请联系作者获取转载授权,否则将追究法律责任
#include <fstream>
#include <cstdlib>
const int SIZE = 60;
int main()
{
using namespace std;
char filename[SIZE] = "C:/Users/yulong/Desktop/";
char fileuser[30];
cout << "Enter the file name: ";
cin.getline(fileuser,30);
strcat_s(filename,fileuser);
cout << "filename: " << filename << endl;
ifstream infile;
infile.open(filename); //文件内容是1 2 3
if(!infile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
/*以下使用good()的方法只能读到1和2,如果在设定文件内容时在3后面加一空格或者回车可以读到3*/
infile >> value;
while(infile.good())
{
count++;
sum += value;
infile >> value;
}
/*以下方法可以正常读取到3个数字而不需要刻意在3后面加一空格或者是一个回车*/
/* while(infile >> value)
{
count++;
sum += value;
}
*/
if(infile.eof())
cout << "End of file " << filename << endl;
else if(infile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";
if (count == 0)
cout << "No data processed.\n";
else
{
cout << "Items read: " << count << endl;
cout << "Sum: " << sum << endl;
cout << "Average: " << sum/count << endl;
}
infile.close();
return 0;
}
下一篇:我的友情链接
![](https://ucenter.51cto.com/images/noavatar_middle.gif)
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
HDU 4416 Good Article Good sentence
Description
HDU #include i++ #define -
very good
发现51cto的邮件营销做得很好,定期的邮件杂志,让我会开始关注51cto。
职场 杂志 休闲 邮件营销