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.
The whole program is under 40 lines of code. Just read from
cin.
Now, you need to detect non integers. In this case, 100 is an
integer but things like foo or 375.2 or 23skidoo are not.
You can read into integers using cin >> something, but you
need to check for those error cases. The stream will read the
integer and will stop at whatever is not an integer. Maybe (if it
tries to read foo) it fails and you have to clear() the error.
Maybe some number was read but there’s extra characters after... SO
you need to peek at the next character, and if it’s not a space
then it’s one of the error cases. You have to read and throw away
the characters. Look into the peek and get methods on streams, and
use isspace to decide if something is a space or not. Remember that
there may be more than one character to discard.
#include<fstream.h>
#include<string.h>
#include<ctype.h>
int a[1000],p=0,t; //**globally array declared to store integer
value of whole file **//
int total(int val,int sum){return sum=sum*10+val;}
void add(int val){ a[p]=val;p++;} //**add integer in
array**//
int getint(int val){int k=0;for(int i=48;i<val;i++){ k++;}return
k; } //**return integer resides in file**//
void string_detect(char s[100],int n)
{
int sum=0,flag=0;
for(int i=0;i<n;i++)
{
if(isdigit(s[i]))
{
int
no=int(s[i]);
int
value=getint(no);
sum=total(value,sum);
flag=1;
}
if((isspace(s[i+1])&&flag==1)||!isdigit(s[i+1])&&flag==1){add(sum);
sum=0;flag=0;}
}
}
int main()
{
ifstream fin;
fin.open("tejas.txt");
char s[100]; //**maximum length of line is 100 character**//
while(!fin.eof())
{
fin.getline(s,100); //**line by
line scanning**//
string_detect(s,strlen(s));
}
for(int i=0;i<p;i++){ //**sort the array**//
for(int j=i;j<p;j++) //**maximaum value will move
at the end of array**//
{
if(a[i]>a[j]){t=a[i];a[i]=a[j];a[j]=t;}
} }
return a[p-1]; //**return last value of
array**//
}