I have to extract numbers from a string and then add them, but I am stuck and I'm just not sure what to do next if anyone could guide me to get further it would be helpful. I feel dumb for even asking.
prompt:
Write a program that will extract a series of numbers (type double) from an input sentence and then add them. EXAMPLE: Suppose the sentence entered is “Give me the sum of 25.25 and 13.50. ”The program should print to the screen: The sum = 38.75 NOTE: The numbers can be of any value. Don’t hard code to the values shown in the example. In this problem take advantage of the input options presented in class. Particularly cin, cin.get, cin.ignore, and peek.
Test the program with both of these examples:
TEST CASE 1. “Please tell me the sum of 18.0 plus 25.5.”
OUTPUT: "The sum is 43.5
TEST CASE 2. “If I add 24.5, 18.0 and 17.2 what do I get?
OUTPUT: "The sum is 59.7
NOTE: There are several library functions in C++ that will make this problem easier to do. In particular you should consider using the following functions: ch is char type
isalpha(ch) Returns true if ch is a letter (A-Z, a-z)
isdigit(ch) Returns true if ch is a digit (0-9)
ispunct(ch) Returns true if ch is punctuation character (period, comma, question mark etc.)
isspace(ch) Returns true if ch is a space.
For example:
cin.get(ch1); // Read a character
if ( isdigit(ch1) )
cout << "The character is a number." << endl;
You will need to include the cctype library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cctype>
using namespace std;
int main()
{
char str[]="";
cin.get(str[]); // Read a character
if (isdigit(str[0]))
cout << "The character is a number." << endl;
cin.get(str[0]);
if (isalpha(str[0]))
cout << "The chararacter is a digit." << endl;
cin.get(str[0]);
if (ispunct(str[0]))
cout << "The chararacter is a punctuation character." << endl;
cin.get(str[0]);
if (isspace(str[0]))
cout << "The character is a space." << endl;
return 0;
}
|
I have no idea whether I am in the right direction or not but just figured I'd post this.