Sesame
Sesame

Reputation: 47

C++ How to average a string of numbers?

I have a problem with something I was trying to work out.

If I had a string of numbers with spaces like "10 20 30 40", is there any way I can add those numbers up and average them out?

I tried the below code but it returned 'nan', so I don't really know what I'm doing wrong.

for (int i = 0; i < numLength; i++)
{
    num = grades.at(i) - '0';
    total += num;
    countNum++;
}

cout << firstName << " " << lastName << " average: " << (total/countNum) << endl;

Upvotes: 3

Views: 953

Answers (2)

PaulMcKenzie
PaulMcKenzie

Reputation: 35455

Instead of trying to manually parse the data, you can simply use std::istringstream:

#include <string>
#include <sstream>
#include <iostream>

int main()
{
   std::string test = "10 20 30 40";
   int count = 0;
   double total = 0.0;
   std::istringstream strm(test);
   int num;
   while ( strm >> num )
   {
       ++count;
       total += num;
   }
   std::cout << "The average is " << total / count;
}

Output:

The average is 25

Upvotes: 7

Remy Lebeau
Remy Lebeau

Reputation: 596713

Use a std::istringstream to parse the string, eg:

#include <iostream>
#include <string>
#include <sstream>
...

std::istringstream iss(grades);
while (iss >> num) {
    total += num;
    ++countNum;
}
std::cout << firstName << " " << lastName << " average: " << (total/countNum) << std::endl;

Upvotes: 0

Related Questions