相关疑难解决方法(0)

为什么循环条件中的iostream :: eof被认为是错误的?

我刚刚在这个答案中发现了一条评论说iostream::eof在循环条件下使用"几乎肯定是错误的".我通常使用类似的东西while(cin>>n)- 我猜是隐式检查EOF,为什么检查eof显式使用while (!cin.eof())错误?

它与scanf("...",...)!=EOF在C中使用有何不同(我经常使用没有问题)?

c++ iostream c++-faq

564
推荐指数
5
解决办法
6万
查看次数

为什么(foobar >> x)优先于(!foobar.eof())

可能重复:
为什么循环条件中的iostream :: eof被认为是错误的?
eof()不好的做法?

我的老师说我们不应该使用EOF来读取文本文件或二进制文件信息,而应该使用(afile >> x).他没有解释原因,有人可以向我解释.有人也可以解释这两种不同的阅读方法有什么不同

//Assuming declaration 
//ifstream foobar



( ! foobar.eof() )
{
    foobar>>x; // This is discouraged by my teacher

}


 while (foobar>>x)
{
  //This is encouraged by my teacher

}
Run Code Online (Sandbox Code Playgroud)

c++ binaryfiles text-files

9
推荐指数
1
解决办法
393
查看次数

我如何从文件中读取第一行?

ifstream infile;

string read_file_name("test.txt");

infile.open(read_file_name);

string sLine;

    while (!infile.eof())
    {
        getline(infile, sLine);         
        cout << sLine.data() << endl;
    }

    infile.close();
Run Code Online (Sandbox Code Playgroud)

该程序打印文件中的所有行,但我想只打印第一行.

c++

8
推荐指数
1
解决办法
4万
查看次数

c ++用eof()读取未定义的行数

我正在处理使用eof()的问题.运用

string name;
int number, n=0;
while(!in.eof())
{
    in >> name >> number;
    //part of code that puts into object array
    n++;
}
Run Code Online (Sandbox Code Playgroud)

只要文件中没有更多文本,我就听起来很正常.但我得到的是n是4200317.当我查看数组条目时,我看到第一个是文件中的那些,其他是0.

可能是什么问题,我该如何解决?也许有一个替代这个阅读问题(有不确定的行数)

c++ eof

0
推荐指数
1
解决办法
769
查看次数

标签 统计

c++ ×4

binaryfiles ×1

c++-faq ×1

eof ×1

iostream ×1

text-files ×1