Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using eof on C++

i am looking for C++ coding for this pascal code

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

i don't understand using eof on C++

it's purpose is to calculate data from line 1 to the end of the file

edit : well i tried this but no luck

#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;
}

sorry i am new to C++

like image 762
zeulb Avatar asked Dec 05 '22 20:12

zeulb


2 Answers

You're pretty close, but probably being influenced a bit more by your Pascal background than is ideal. What you probably want is more like:

#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;
}

Alternatively, C++ can treat a file roughly like a sequential container, and work with it about like it would any other container:

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;
}
like image 125
Jerry Coffin Avatar answered Dec 27 '22 00:12

Jerry Coffin


The usual idiom is

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

The cin object casts to false after operator>> fails, usually because of EOF: check badbit, eofbit and failbit.

like image 36
spraff Avatar answered Dec 26 '22 23:12

spraff