Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Task 1 Task 1.1 Write a function called ? is_int ? that returns a boolean ? true

ID: 3912733 • Letter: T

Question

Task 1

Task 1.1

Write a function called ?is_int? that returns a boolean ?true?/?false? depending on whether an input string is an integer or not.

For example: ?an input of ?“123”? would return ?true?, and an input of ?“abc123”? would return ?false Task 1.2

Write a function that accepts a reference to any ?istream? object (?cin?, ?ifstream?, ?istringstream?, etc.) Call it ?sum_integers?. This function will return the sum of all whitespace separated integers within the input to the ?istream

For example?: ?Say I pass an?? istringstream?? pointing to the string?? “1 egg, 2 cups flower, 2 tbsp sugar”?.? ?Then?? sum_integers?? shouldreturn5?.

Name your file task1.cpp

Explanation / Answer

Here i have written two seperate codes with main(), so take the only required fucnctions implemented in the code. THE FIRST CODE IS for task 1.1 to check wether an input alphanumeric string consists only of numbers or not.

#include<iostream>
using namespace std;
bool is_int(string str)
{
int len = str.length();
int check = 1;
for(int i=0;i<len;i++)
{
int val = (int)str[i];
if(val < 48 || val > 57) /*condition to check if ascii value lies between ascii value of 0 to 9 or not*/
check =0;
}
if(check == 0)
return false;
else
return true;
}
int main()
{
cout<<"Enter the string containing number or is alphanumeric"<<endl;
string str;
cin>>str;
bool x = is_int(str);/* calling my is_int function to check if string consists only of numbers or not*/
cout<< x<<endl;
cout<<"if x is 1 means true and 0 means false in c++"<<endl;
}

/*

THIS IS CODE TO IMPLEMENT TASK 1.2

sum_integer function has been implementd to calculate the sum of all integer value present in the txt file

To run this code using main method implementd here make your own txt file and run the code to check for varios test cses.

*/

#include<bits/stdc++.h>
using namespace std;
/*
passing stream object to sum_integer;
*/
int sum_integers(istream& stream)
{
string line; /* this holds complete file in a string*/
getline(stream ,line);
int sum =0;

cout<<line<<endl;

for(int i=0;i<line.length();i++)
{

int val = (int)line[i];

if(val >= 48 && val <= 57)
{
sum = sum + val - 48;
}
}
return sum;
}
int main()
{
string line;
int x;
ifstream myfile("abc.txt");
/*
reading the file using fstream;
*/
if(myfile.is_open())
{
while(myfile.good())
{
x = sum_integers(myfile);
}
}
else
{
cout<<"unable to open file"<<endl;
}
cout<<"Sum ="<<x<<endl;
}
/*
make a txt file abc.txt to check this code
*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote