[英]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.你好,我写了一个算法,它打印最后一个数字,但我想知道当控制台/文件中没有数字时,如何使它不打印“数字”的默认值,例如(4.94066e-324)。
#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:我在这里改变了几件事:
using namespace std;
using namespace std;
删除using namespace std;
, it's considered bad parctice while
is better suited for this task than a half-empty for
while
更适合这项任务不是半空for
And of course this can be generalized to any std::basic_istream
.当然,这可以推广到任何
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.