Hello,
I recently finished a tutorial on C++ and I have written a small program. Could you please take a look at my code and give me feedback on it?

It's a program that will ask you for two values and then add them together.

Please be nice, since it's my first "non-tutorial" program and I just turned 13.

/*
 * My first program that wasn't from a tutorial.
 * (C) 2007 Laseredd.
 */

#include <iostream>
#include <string>
#include <sstream>
using namespace std; 

class Calc 
{
	int num1, num2;
   	public:
   	void set_num(int, int);
   	int add();
};

void Calc::set_num(int a, int b)
{
	num1 = a;
	num2 = b;
}

int Calc::add()
{
	return (num1 + num2);
}

int main()
{
	Calc calc;
	string valid;
	int numb1, numb2;
	
	cout << "What numbers to you want to add? " << endl;
	
	cout << "Number 1: ";
	getline(cin, valid);
	stringstream(valid) >> numb1;
	
	cout << "Number 2: ";
	getline(cin, valid);
	stringstream(valid) >> numb2;
	
	calc.set_num(numb1, numb2);
	cout << calc.add();
	
	return 0;
}
Comments
Looks good

How to judge this depends on what your intentions were when writing it...

As a means of adding 2 numbers it's overly complicated, as a way of learning how simple classes can be written it's not bad.

Hi Laseredd,

That short program looks good! I think you have shown understanding of some very important C++ principles here, classes, methods, I/O. :)
As an extension, how do you think you would go about accepting either integers or floats rather than just integers? Can you think of how your Calc class might be written to accept two strings and concatenate them together (add the second onto the end of the first)?

darkagn

You can add validation to your code by doing somthing like this

#include <iostream>
#include <algorithm>
#include <sstream>

using namespace std;

struct nondigit
{
public:
    bool operator() (char ch)
    {
        return !isdigit(ch);
    }
};


int main()
{
    int num;
    string str;
    bool flag=false;
    cout<< "Enter number: "<< endl;
    cin>>str;

    //make sure that num contains digits exclusively
    if(find_if(str.begin(),str.end(), nondigit())==str.end())
        flag=true; // we have a valid string
    else
        cout<<"Invalid Input";

    if(flag==true)
    {
        stringstream temp(str); //insert string to temp
        temp>>num; //extract int value and write it to num
        cout<<num;
    }

    return 0;
}
This article has been dead for over six months. Start a new discussion instead.