Extract and Add a Series of Numbers

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.
the language can do this, using stod (string to double) and similar functions for one approach.

to do it yourself for simple decimal formats, its just powers of 10.
say they type in 123.456 (and you skipped over any other junk, spaces, letters, whatever?)

up to the decimal point:
double value{0.0};
for(... valid letters in str)
{
value *= 10; //0*10 is 0 //1*10 is 10 // 12*10 is 120
value += letter-'0'; //0+1 is 1 //10 + 2 is 12 //120+3 is 123
}
and after the decimal point you add fractions in a similar way, 1/10 + 1/100th ... etc inverse of teh above idea. Remember to start with tenths, not ones, for the second loop.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <sstream>

int main()
{
	const std::string input {"If I add 24.5, 18.0 and 17.2 what do I get?"};
	std::istringstream iss(input + " ");

	double t {};

	for (double n {}; !(iss >> n).eof(); t += n)
		if (!iss)
			for (n = 0, iss.clear(); iss.get() != ' '; );

	std::cout << "The sum is " << t << '\n';
}



The sum is 59.7

Last edited on
You are all ignoring the clear instructions OP was given, including the very specific list of functions to use.

OP is expected to find and parse the numbers himself. Not use library functions or classes to parse the string.


OP will need a loop to find where the numbers are in the input. Every time you find a digit you have found the beginning of a number.

Hint: use cin.get() to get the next character from input.

Hint: use isdigit() to check whether or not that character is a digit.

Hint: you can also compare directly with characters (like '.').

1
2
3
4
5
6
  char c;
  while (std::cin.get( c ))
  {
    if (std::isdigit( c ))
      ...
  }

Building a number yourself is not difficult, but will require a little effort. You could also just copy the digits to a string and use atof() or something once you get to the end of the number.

The last thing to remember is that you are keeping a running total. So you should start with

 
  double sum = 0.0;

Each time you get a complete number, add it to the sum.
Then, once you get to the end of input just print the sum.

Good luck!
You are all ignoring the clear instructions OP was given, including the very specific list of functions to use.


No I'm not. The instructions:

Write a program that will extract a series of numbers (type double) from an input sentence and then add them .... 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 ... There are several library functions in C++ that will make this problem easier to do. In particular you should consider using the following functions:


There is no requirement to use the listed cctype functions. They are only given as some that may be useful. It doesn't say you have to use them.

The lecturer may expect this exercise to be done one way - but the instructions don't preclude other ways.
Last edited on
@Duthomhas I'm just a little stumped as to what to put under the if statement and is it necessary to use isspace, isspunc, etc?

Here's my code so far hopefully I am getting somewhere
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cctype>

using namespace std;

int main()
{
    char c;
    double sum = 0.0;
    string s = "";
    getline(cin, s);
    while (cin.get(c))
    {
    if (isdigit(c))
    c += sum;
    cout << sum << endl;
    }
    return 0;
}
Using cin.get() and a cctype function, then perhaps:

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
26
27
28
#include <iostream>
#include <cctype>

int main()
{
	double tot {};

	for (auto ch {std::cin.get()}; ch != '\n'; )
		if (isdigit(ch) || ch == '.') {
			bool pt {ch == '.'};
			double num = pt ? 0 : ch - '0';

			for (double dec {1}; (ch = std::cin.get()) == '.' || isdigit(ch); )
				if (isdigit(ch))
					num = pt ? num + (dec /= 10) * (ch - '0') : num * 10 + ch - '0';
				else {
					if (pt)
						break;

					pt = true;
				}

			tot += num;
		} else
			ch = std::cin.get();

	std::cout << "The total is " << tot << '\n';
}



If I add 24.5, 18.0 and 17.2 what do I get
The total is 59.7

The lecturer may expect this exercise to be done one way - but the instructions don't preclude other ways.

That may be so, but when the lecturer says here are some functions you may find useful that's a pretty heavy hint that you ought to put one or two of them to use.

Because if you (or someone on the internet) can do much better, then why are you taking the course?

How often do we want to believe we know better than the instructor what he intends to teach, and how to teach it?

Or shall we continue with the "all university CS 101 instructors are garbage" absurdism?

Mayhaps we should consider that the instructor's course of action is a little better thought than we might want to think in our two-to-three seconds of superior consideration?
@Duthomhas

Who's gunning for you?

I thought your 2 responses on this thread were clear, concise and very useful. And both were reported. Boo!

I think it's important that we remember that the instructor is the authority, and we are helping the students satisfy their requirements. Providing code suggestions that jump ahead in the syllabus don't help the students.

Granted, there are instructors who have extremely outdated methods and approaches, but I think we owe it to the students to help them meet the instructor's requirement FIRST before showing alternate methods that might be more efficient.

It wasn't me.
I offended him in another thread.

Rather than accept that Things Don't Always Go Your Way On The Internet™ he decided to go and report everything I've ever written.



Ignore it. It's happened before and means nothing.






I know it wasn't seeplus. He's too cool to be easily offended by a minor difference of opinion.
Topic archived. No new replies allowed.