Question
C++ with comments please!

The following program will read a number from the user and store the number as a string of characteristics. Convert this stri

// numberverifier.cpp
#include <iostream>
#include <exception>

using std::cout;
using std::cin;
using std::endl;

#include <cmath>
#include <cstring>

class nonNumber : public exception {
public:
/* write definition for the constructor */ -- Message is “An invalid input was entered”

};



int castInput( char *s )
{
char *temp = s;
int result = 0, negative = 1;

// check for minus sign
if ( temp[ 0 ] == '-' )
negative = -1;

for ( int i = strlen( s ) - 1, j = 0; i >= 0; i--, j++ ) {
if ( negative == -1 && i == 0 )
continue;

if ( isdigit( temp[ i ] ) )
result += ( temp[ i ] - '0' ) * pow( 10, j );   
else
/* write code to throw nonNumber exception */

}

return result * negative;
}

int main()
{
char input[ 100 ];
int convert;
cout << "Please enter a number (EOF to end): ";

while ( cin >> input ) {

/* write try block that calls castInput */
/* write catch statement that catches any exceptions
that the call to castInput might have thrown */


cout << "\n\nPlease enter a number (EOF to end): ";
}

cout << endl;
return 0;
}





0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <iostream>
#include <exception>

using std::cout;
using std::cin;
using std::endl;
using std::exception;
#include <cmath>
#include <cstring>

class nonNumber : public exception {
public:
virtual const char* what() const throw()//exepction handler error containd in what() function
{
return "INVALID INPUT: Non-Integer detected";
}

} ex;//exeption instance created

int castInput( char *s )
{
char *temp = s;
int result = 0, negative = 1;

// check for minus sign
if ( temp[ 0 ] == '-' )
negative = -1;

for ( int i = strlen( s ) - 1, j = 0; i >= 0; i--, j++ ) {
if ( negative == -1 && i == 0 )
continue;
  
if ( isdigit( temp[ i ] ) )
result += ( temp[ i ] - '0' ) * pow( 10, j );   
else
throw nonNumber();
// throwing the error to the non number exception class


}
return result * negative;
}

int main()
{
char input[ 100 ];
int convert;
cout << "Please enter a number (EOF to end): ";

while ( cin >> input ) {

try{
convert=castInput(input);
cout<<"The number entered Was "<<convert;
}
catch(nonNumber& ex){
cout<<ex.what()<<endl;//what() Method contains specific error message it is called with ex instance here
  
}
cout << "\n\nPlease enter a number (EOF to end): ";


}

cout << endl;
return 0;
}

Here is the output:

:Please enter a number (EOF to end) : 44 The number entered Was 44 Please enter a number (EOF to end): ff INVALID INPUT: Non-I   

Add a comment
Know the answer?
Add Answer to:
C++ with comments please! // numberverifier.cpp #include <iostream> #include <exception> using std::cout; using std::cin; using std::endl;...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write following program using Switch statement. #include <iostream> using namespace std; int main() int number; cout...

    Write following program using Switch statement. #include <iostream> using namespace std; int main() int number; cout << "Enter an integer cin >> number; if (number > B) cout << You entered a positive integer: " << number << endl; else if (number (8) cout<<"You entered a negative integer: " << number << endl; cout << "You entered e." << endl; cout << "This line is always printed." return 0;

  • #include <iostream> #include <conio.h> #include<limits> using namespace std; int main(){ char oparand, ch = 'Y'; int...

    #include <iostream> #include <conio.h> #include<limits> using namespace std; int main(){ char oparand, ch = 'Y'; int num1, num2, result; while(ch == 'Y'){ cout << "Enter first number: "; cin >> num1; while(1){//for handling invalid inputs if(cin.fail()){ cin.clear();//reseting the buffer cin.ignore(numeric_limits<streamsize>::max(),'\n');//empty the buffer cout<<"You have entered wrong input"<<endl; cout << "Enter first number: "; cin >> num1; } if(!cin.fail()) break; } cout << "Enter second number: "; cin >> num2; while(1){ if(cin.fail()){ cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout<<"You have entered wrong input"<<endl; cout <<...

  • #include <iostream> using namespace std; int main(void) {    int SIZE;    cout<<"Enter the size of the...

    #include <iostream> using namespace std; int main(void) {    int SIZE;    cout<<"Enter the size of the array"<<endl;    cin>>SIZE;     int *numlist = new int[SIZE];     // Read SIZE integers from the keyboard     for (int i = 0; i<SIZE; i++ )    {        cout << "Enter value #" << i+1 << ": ";        cin >> numlist[i];     }     // Display the numbers in a reverse order     for (int i = SIZE; i > 0; i--...

  • Write a psuedocode for this program. #include <iostream> using namespace std; string message; string mappedKey; void...

    Write a psuedocode for this program. #include <iostream> using namespace std; string message; string mappedKey; void messageAndKey(){ string msg; cout << "Enter message: "; getline(cin, msg); cin.ignore(); //message to uppercase for(int i = 0; i < msg.length(); i++){ msg[i] = toupper(msg[i]); } string key; cout << "Enter key: "; getline(cin, key); cin.ignore(); //key to uppercase for(int i = 0; i < key.length(); i++){ key[i] = toupper(key[i]); } //mapping key to message string keyMap = ""; for (int i = 0,j...

  • C++ #include <iostream> using namespace std; bool checkinventoryid(int id) {    return id > 0; }...

    C++ #include <iostream> using namespace std; bool checkinventoryid(int id) {    return id > 0; } bool checkinventoryprice(float price) {    return price > 0; } void endProgram() {    system("pause");    exit(0); } void errorID(string str) {    cout << "Invalid Id!!! " << str << " should be greater than 0" << endl; } void errorPrice(string str) {    cout << "Invalid Price!!!" << str << " should be greater than 0" << endl; } int inputId() {...

  • Use C++ #include <iostream> #include <stdlib.h> #include <stdio.h> #include <cstring> using namespace std; /I Copy n...

    Use C++ #include <iostream> #include <stdlib.h> #include <stdio.h> #include <cstring> using namespace std; /I Copy n characters from the source to the destination. 3 void mystrncpy( ???) 25 26 27 28 29 11- 30 Find the first occurrance of char acter c within a string. 32 ??? mystrchr???) 34 35 36 37 38 39 / Find the last occurrance of character c within a string. 40 II 41 ??? mystrrchr ???) 42 43 45 int main() char userInput[ 81]; char...

  • #include <fstream> #include <iostream> #include <cstdlib> using namespace std; // Place charcnt prototype (declaration) here int...

    #include <fstream> #include <iostream> #include <cstdlib> using namespace std; // Place charcnt prototype (declaration) here int charcnt(string filename, char ch); int main() { string filename; char ch; int chant = 0; cout << "Enter the name of the input file: "; cin >> filename; cout << endl; cout << "Enter a character: "; cin.ignore(); // ignores newline left in stream after previous input statement cin.get(ch); cout << endl; chcnt = charcnt(filename, ch); cout << "# of " «< ch« "'S:...

  • I NEED A PSEUDOCODE ALGORITHM FOR THIS CODE PLEASE C++: #include #include #include #include using...

    I NEED A PSEUDOCODE ALGORITHM FOR THIS CODE PLEASE C++: #include #include #include #include using namespace std; int NumOfEmployees(); int TotDaysAbsent(int); double AverageAbsent(int, int); int main() {         cout << endl << "Calculate the average number of days a company's employees are absent." << endl << endl;      int numOfEmployees = NumOfEmployees();         TotDaysAbsent(numOfEmployees);    return 0; } int NumOfEmployees() {    int numOfEmployees = 0;     cout << "Please enter the number of employees in the company: ";         cin >> numOfEmployees;     while(numOfEmployees <= 0)     {            ...

  • #include <iostream> #include <string> using std::string; using std::cout; using std::endl; void testAnswer(string testname, int answer, int...

    #include <iostream> #include <string> using std::string; using std::cout; using std::endl; void testAnswer(string testname, int answer, int expected) { if (answer == expected) cout << "PASSED: " << testname << " expected and returned " << answer << "\n"; else cout << "FAILED: " << testname << " returned " << answer << " but expected " << expected << "\n"; } // Implement printArray here void printArray(int array[],int b) { for(int i = 0; i<b;i++) { std::cout<< array[i] << "...

  • #include<iostream> using namespace std; int main() { float num,avg,sum=0.0; int count=0; bool moreNumbers=true; cout<<"Enter grades:"<<endl; while(moreNumbers)...

    #include<iostream> using namespace std; int main() { float num,avg,sum=0.0; int count=0; bool moreNumbers=true; cout<<"Enter grades:"<<endl; while(moreNumbers) { cin>>num; if(num < 0) { moreNumbers=false; } else { count = count+1; sum=sum+num; } } avg=sum/count; cout<<"Average grade:"<<avg<<endl; cout<<"How many grades were entered:"<<count<<endl; return 0; } Question: We need to add another loop to check input. Just like the input loop we already have, this one should use a boolean variable as a control. So, the logic could be something like this: Loop...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT