In: Computer Science
Write a C++ program that reads integers from standard input until end of file.
Print out the largest integer that you read in, on a line by itself.
Any erroneous input (something that is not an integer) should be detected and ignored.
In the case where no integers are provided at all, print NO INTEGERS and stop.
Remember, try not to do the entire job all at once! First try input of a single number and make sure it works. Make sure that you detect eof correctly. Then add the error checks. Then add the loop...
#include <iostream> #include <iomanip> #include <string> #include <cstdlib> using namespace std; bool isNumber(const string s){ return s.find_first_not_of( "0123456789" ) == string::npos; } int main() { int totalNums = 0; int largest = 0; // read from stdin untill EOF string x; while(cin >> x) { if(isNumber(x)) { if(totalNums == 0) { largest = atoi(x.c_str()); } else if(largest < atoi(x.c_str())) { largest = atoi(x.c_str()); } totalNums++; } } if(totalNums == 0) { cout << "NO INTEGERS" << endl; } else { cout << "Max: " << largest << endl; } }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.