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++
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With