Reputation: 31
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; }
Upvotes: 0
Views: 132
Reputation: 1
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;
}
Upvotes: 0
Reputation: 11370
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:
using namespace std;
, it's considered bad parcticewhile
is better suited for this task than a half-empty for
And of course this can be generalized to any std::basic_istream
.
Upvotes: 2