繁体   English   中英

在C ++上使用eof

[英]using eof on C++

我正在寻找这个pascal代码的C ++编码

var
jumlah,bil : integer;
begin
jumlah := 0;
while not eof(input) do
begin
   readln(bil);
   jumlah := jumlah + bil;
end;
writeln(jumlah);
end.

我不明白在C ++上使用eof

它的目的是计算从第1行到文件末尾的数据

编辑:我试过这个,但没有运气

#include<iostream>
using namespace std;

int main()
{
    int k,sum;
    char l;
    cin >> k;
    while (k != NULL)
    {
          cin >> k;
          sum = sum + k;
    }
    cout << sum<<endl;
}

对不起,我是C ++的新手

通常的习语是

while (std :: cin >> var) {
   // ...
}

operator>>失败后, cin对象被转换为false,通常是因为EOF: 检查badbit,eofbit和failbit

你非常接近,但是你的Pascal背景可能比理想的更多。 你可能想要的更像是:

#include<iostream>
using namespace std;   // Bad idea, but I'll leave it for now.

int main()
{
    int k,sum = 0; // sum needs to be initialized.
    while (cin >> k)
    {
          sum += k;  // `sum = sum + k;`, is legal but quite foreign to C or C++.
    }
    cout << sum<<endl;
}

或者,C ++可以将文件大致视为顺序容器,并且可以像处理任何其他容器一样使用它:

int main() { 
    int sum = std::accumulate(std::istream_iterator<int>(std::cin), 
                              std::istream_iterator<int>(),
                              0);    // starting value
    std::cout << sum << "\n";
    return 0;
}

要格式化David在上面写的内容:

#include <iostream>
#include <string>

int main()
{
    int jumlah = 0;
    std::string line;
    while ( std::getline(std::cin, line) )
        jumlah += atoi(line.c_str());

    std::cout << jumlah << std::endl;
    return 0;
}

您还可以在http://www.cplusplus.com/reference/iostream/上找到更多信息

暂无
暂无

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

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