简体   繁体   中英

End of File (EOF)

Hello I've written an algorithm where it prints last number , but I wonder how to make it not to print default value of "number" for example(4.94066e-324) when there's no number written in console/file.

#include <iostream>
using namespace std;

int main() {
double number;
for (; cin >> number;);
cout << number; }

One way is to check wether the first input operation succeeds or not:

#include <iostream>

int main() {
    double number;

    if(std::cin >> number)
    {
        while (std::cin >> number);

        std::cout << number; 
    }
    else 
    {
        std::cout << "There is no number :(";
    }
}

Few things I changed here:

  • removed using namespace std; , it's considered bad parctice
  • a while is better suited for this task than a half-empty for

And of course this can be generalized to any std::basic_istream .

You can use a flag to check if you have ever got any input, like this:

#include <iostream>
using namespace std;

int main() {
    double number;
    bool flag = false;
    for (; cin >> number;)
        flag = true;
    if(flag)
        cout << number; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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