开发者

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 &g开发者_如何学JAVAt;> 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.


To format what David wrote above:

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

You can also find more information at http://www.cplusplus.com/reference/iostream/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜