1

I have the following lines of code:

vector<string> c;
string a;
for(int i=0;i<4;i++){
   cin>>a;
   c.push_back(a);
}

If I provide input as:

120$,132$,435$,534$

How can I extract the integer values separately and add them up to get the total value?

eraxillan
  • 1,552
  • 1
  • 19
  • 40
ejjyrex
  • 1,151
  • 1
  • 10
  • 13
  • If you always know the last char is a dollar sign then use the substring method to retrieve the numerical part, convert it to an int and add. – Vaibhav Desai Nov 08 '12 at 08:50
  • Isn't this a duplicate of http://stackoverflow.com/questions/2392397/going-through-a-string-of-characters-and-extracting-the-numbers or http://stackoverflow.com/questions/9515845/extract-numbers-from-string-c? – jogojapan Nov 08 '12 at 08:53

4 Answers4

4

You can use e.g. std::getline with a custome "line" separator using the comma, strip the last character from the string (the '$') and use std::stoi to convert to an integer:

std::vector<int> c;

for (int i = 0; i < 4; i++)
{
    std::string a;
    std::getline(std::cin, a, ',');

    a = a.substr(a.length() - 1);  // Remove trailing dollar sign

    c.push_back(std::stoi(a));
}

Edit: Using std::accumulate:

int sum = std::accumulate(c.begin(), c.end(), 0);

Edit 2: Using std::strtol instead of std::stoi:

The function std::stoi is new in the latest C++ standard (C++11) and it not supported in all standard libraries yet. Then you can use the older C function strtol:

c.push_back(int(std::strtol(a.c_str(), 0, 10)));
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

You can use regex and streams:

#include <regex>
#include <iostream>
#include <sstream>

const std::string Input("120$,132$,435$,534$");

int main(int argc, char **argv)
{
    const std::regex r("[0-9]+");
    int Result = 0;

    for (std::sregex_iterator N(Input.begin(), Input.end(), r); N != std::sregex_iterator(); ++N)
    {
        std::stringstream SS(*N->begin());
        int Current = 0;
        SS >> Current;
        Result += Current;
        std::cout << Current << '\n';
    }

    std::cout << "Sum = " << Result;

    return 0;
}

Output:

120
132
435
534
Sum = 1221

If you must ensure that the number is followed by a '$' then change the regex to: "[0-9]+\\$" the stringstream part will ignore the trailing '$' in the number conversion:

#include <regex>
#include <iostream>
#include <sstream>

const std::string Input("120$,132$,435$,534$,1,2,3");

int main(int argc, char **argv)
{
    const std::regex r("[0-9]+\\$");
    int Result = 0;

    for (std::sregex_iterator N(Input.begin(), Input.end(), r); N != std::sregex_iterator(); ++N)
    {
        std::stringstream SS(*N->begin());
        int Current = 0;
        SS >> Current;
        Result += Current;
        std::cout << Current << '\n';
    }

    std::cout << "Sum = " << Result;

    return 0;
}

Output:

120
132
435
534
Sum = 1221
PaperBirdMaster
  • 12,806
  • 9
  • 48
  • 94
1

If the input isn't too large (and particularly if it comes as a single line), the simplest solution is to pack it all into a string, and parse that, creating a std::istringstream to convert each of the numeric fields (or using boost::lexical_cast<>, if by some odd chance it has the appropriate semantics—it normally does when translating a string to a built-in numeric type). For something this simple, it's possible, however, to read directly from a stream, however:

std::istream&
ignoreDollar( std::istream& stream )
{
    if ( stream.peek() == '$' ) {
        stream.get();
    }
    return stream;
}

std::istream&
checkSeparator( std::istream& stream )
{
    if ( stream.peek() == ',' ) {
        stream.get();
    } else {
        stream.setstate( std::ios_base::failbit );
    }
    return stream;
}

std::vector<int> values;
int value;
while ( std::cin >> value ) {
    values.push_back( value );
    std::cin >> ignoreDollar >> checkSeparator;
}
int sum = std::accumulate( values.begin(), values.end(), 0 );

(In this particular case, it might be even simpler to just do everything in the while loop. The manipulators are a generally useful technique, however, and can be used in a wider context.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • ...Can you please show me how to do it the way I want it. Suppose using vector I have collection of strings as `123$ 324$ 453$ 545$ Now I need to find the sum of all this inputs. So how should I accomplish it?? – ejjyrex Nov 08 '12 at 10:07
  • @ejjy Just convert the strings to numbers, using the techniques above, then `std::accumulate` on the numbers. (You might want to define a converter object, and use `std::transform` on the vector of strings.) – James Kanze Nov 08 '12 at 11:54
1

A simple version:

int getIntValue(const std::string& data)
{
  stringstream ss(data);
  int i=0;
  ss >> i;
  return i;
}

int getSum(std::vector<std::string>& c)
{
  int sum = 0;  
  for (auto m = c.begin(); m!= c.end(); ++m)
  {
    sum += getIntValue(*m);
  }
  return sum;
}

Done

billz
  • 44,644
  • 9
  • 83
  • 100