Click here to Skip to main content
15,898,035 members

Decimal to Binary program, need feedback

wohstihs asked:

Open original thread
Wrote a program to convert a number to binary in C++ .I'm fairly new to C++ and I did this before and it wasn't done too well, but I feel like I made a few improvements. Please if there are any bad practices or something I might have done wrong, let me know. I know my naming isn't too well but i don't put much thought into that. Thanks.

C++
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <fstream>
#include "modeset.h"
#include <locale>
#include <sstream>


using std::cout;
using std::cin;
using std::vector;
using std::string;
using std::endl;
using std::cerr;
using std::stringstream;


int convert_to_bin(int user_conv_num)
{
    stringstream bin_in_string;//stringstream to store int result in

    if(user_conv_num == 0)
    {

        return 0;

    }


     convert_to_bin(user_conv_num / 2);//We call convert_to_bin function while dividing user_conv_num in the parameter because the modulus operator does not divide for us


     bin_in_string<<user_conv_num % 2;//Get the reminder using the modulus operator, this does not divide user_conv_num by two, it only gets the remainder and writes it to bin_in_string


     cout<<bin_in_string.str();//print result

     return 0;
}

int main()
{
    long int user_conv_num = 0;


cout<<"(#)";

cin>>user_conv_num;


    try
    {


      if(user_conv_num < 0) //if negative number
        throw 1; //throw int exception


      else
        {

        convert_to_bin(user_conv_num); //if not a negative number , do the conversion

        }

    }

    catch (int) //catch int exception if true
    {

        cerr<<"Negative integer";

    }

}
Tags: C++

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900