Binary number function - c++

#include <iostream>
using namespace std;
void binary(unsigned a) {
int i;
cout << "0" << endl;
do {
for (i = 1; i < a; i=i/2) {
if ((a & i) != 0) {
cout << "1" << endl;
}
else {
cout << "0" << endl;
}
}
}
while (1 <= a && a <= 10);
}
int main(void) {
binary(4);
cout << endl;
}
I wrote a code about binary numbers. İt should give bits respect to entering number like for
4 (0100) for 2 (10). However my code goes infinity could you explain. I wrote in visual
studio and I cannot use <bits/stdc++.h> because there is no such a library in visual studio

Initially i is 1 but i = i / 2 sets i to 0, where it remains. The inner loop, therfore, loops for ever.
To output an unsigned number a in binary, use
#include <bitset>
#include <climits>
std::cout << std::bitset<sizeof(a) * CHAR_BIT>(a) << '\n';
(There is, at the time of writing no std::bin i/o manipulator cf. std::hex.)

Without using a built-in function, you can write your own function and perform your operation as follows.
Solution-1
#include <iostream>
void binary(unsigned int number)
{
if (number / 2 != 0) {
binary(number / 2);
}
std::cout << number % 2;
}
int main() {
binary(10);
}
Solution-2
#include <iostream>
#include<string>
void binary(unsigned int number)
{
std::string str = "";
while (number != 0) {
str = (number % 2 == 0 ? "0" : "1") + str;
number /= 2;
}
std::cout << str;
}
int main()
{
binary(4);
}
Note : Don't use using namespace std; . Why is "using namespace std;" considered bad practice?

Related

Unable to assign a range sub-string to an array of strings. c++

So I'm unable to create a substring cut using ranges. I am making an airport program where you feed the program a txt.file and it has to divide the lines I get from it into different strings. For instance, I have the following text data:
CL903 LONDON 41000 14.35 08906 //number of flight, destination, price, etc.
UQ5723 SYDNEY 53090 23.20 12986
IC5984 TORONTO 18030 04.45 03260
AM608 TOKYO 41070 18.45 11315
so the first string will be on the lines of this (variables are in Spanish):
numVuelo[n] = M[n].substr(0,5)
this line will work perfectly, but when I move to the next one (from 7 to 14), it tells me that it's out of range, even though It's between the 0 and 31st values of the length of the string.
M[n] gets all of the strings on the text, I'm using Codeblocks and a class style with header and all. I'll copy the code below...
This is my header Vuelo.h:
#ifndef VUELO_H
#define VUELO_H
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
class Vuelo
{
public:
Vuelo(int N);
virtual ~Vuelo();
void setM();
void setNumVuelo(string _numVuelo, int n);
void setDestino(string _destino, int n);
void setPrecio(string _precio, int n);
private:
string M[NUM_FLIGHTS];
string numVuelo[NUM_FLIGHTS];
string destino[NUM_FLIGHTS+1]; //somehow "destino" doesn't work without the +1 but everything else does
float precio[NUM_FLIGHTS];
Then, on another code called Vuelo.cpp I have the following
#include "Vuelo.h"
Vuelo::Vuelo(int N)
{
M[N] = { };
numVuelo[N] = { };
destino[N] = { };
precio[N] = { };
}
Vuelo::~Vuelo()
{
//nope
}
void Vuelo::setM()
{
int c = 1;
string s;
ifstream F ("flights.txt");
if(F.is_open())
{
while (!F.eof())
{
getline(F,s);
M[c] = s;
cout << M[c] << endl;
c++;
}
//sets all values
for(c = 0; c < NUM_FLIGHTS; c++)
{
setNumVuelo(M[c],c);
setDestino(M[c],c);
setPrecio(M[c],c);
}
F.close();
}
else
{
cout << "ERROR document wasn't found" << endl;
}
}
void Vuelo::setNumVuelo(string _numVuelo, int n)
{
numVuelo[n]= _numVuelo.substr(0,5); //this works
cout << numVuelo[n] <<endl;
}
void Vuelo::setDestino(string _destino, int n)
{
destino[n] = _destino.substr(7, 13); //PROBLEM HERE
cout << destino[n] << " " << destino[n].length() << endl;
}
void Vuelo::setPrecio(string _precio, int n)
{
string p = _precio.substr(15,19); //PROBLEM HERE
precio[n] = atof(p.c_str());
cout << precio[n] <<endl;
}
And finally my main looks like this:
#include "Vuelo.h"
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
int main()
{
cout << "Bienvenido, reserva tu vuelo!" << endl;
cout << "-----------------------------------" << endl;
Vuelo* flight = new Vuelo(NUM_FLIGHTS);
flight->setM();
return 0;
}
Thanks :)

Defining a string in an if statement

Im trying to make a number that is positive (already converted into a string) look like "+number" instead of "number" but i can't define it in an if
#include <iostream>
#include <string>
int main()
{
std::string x3s;
int number = 145;
if (number >= 0)
{
x3s = "+" + number;
}
std::cout << x3s << std::endl;
}
Firstly, there is an I/O manipulator std::showpos.
#include <iostream>
int main()
{
int number = 145;
std::cout << std::showpos << number << std::endl;
}
Secondly, you are using the verb "define" incorrectly.
You can use x3s = std::string("+") + std::to_string(number);

Can't put class with main function?

Something I am working on is making a code that focuses on making a class that reverses an order of numbers. This will then get put into the main code that will eliminate any trailing zeroes. I can't seem to wrap my head around how classes work and where I am going wrong. Here is my code:
Numbers.h
#pragma once
#include <iostream>
class Numbers
{
public:
int digit
private:
void Numbers::reverse();
};
Numbers.cpp
#include "Numbers.h
#include <iostream>
using namespace std;
void Numbers::reverse(){
int n, reversedNumber = 0, remainder;
cout << "Enter the number you would like to manipulate! " << endl;
cin >> n;
while (n !=0)
{
remainder = n % 10;
reversedNumber = reversed Number * 10 + remainder;
n /= 10;
}
//return *this;
}
Main.cpp
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include "Numbers.h"
using namespace std;
int main()
{
Numbers.reverse;
system("pause");
return 0;
}
I can't seem to make the reverse function in my Numbers.cpp work in the main function. I am new to C++ and am not sure where I am going wrong. Any help would be appreciated!
OK, there are a lot of mistakes or learning errors in your code. Your header file should look something like:
#pragma once
class Numbers
{
public:
Numbers();
~Numbers();
int Reverse(int input); // Function is 'public'.
};
Your CPP file will then be (parts taken from S.O. post here):
#include "Numbers.h"
Numbers::Numbers()
{
}
Numbers::~Numbers()
{
}
// No need to store the value in 'digit' since this
// is just an algorithm which can return the result.
int Numbers::Reverse(int input)
{
int ret = 0;
while(input > 0)
{
ret = ret * 10 + (input % 10);
input = input / 10;
}
return ret; // Return the reversed number and let the user decide what to do.
}
Then you can use your class as follows:
#include "Numbers.h"
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number to reverse: ";
cin >> num;
Numbers numClass;
cout << "Reversed number is: " << numClass.Reverse(num) << endl;
return 0;
}

Sorting Genome Strings in C++

I'm creating a program that is meant to sort genome strings, and I've run into an issue with the output.
Code:
#include <iostream>
#include <string>
#include <cctype>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
string genome;
cout << "Enter a genome string: ";
cin >> genome;
int geneCounter = 0;
while(!genome.empty()) //enters loop if strings not empty
{
if(genome.find("ATG") == string::npos)
{
if(geneCounter == 0)
{
cout << "No gene is found";
genome.clear();
}
return 0;
}
else
{
int startGene = genome.find("ATG");
int endGene = min(min(genome.find("TAG"), genome.find("TAA")), genome.find("TGA"));
string currentGene = genome.substr(startGene + 3, endGene - (startGene +3));
if((currentGene.length() % 3) == 0)
{
geneCounter += 3;
cout << currentGene <<endl;
}
endGene += 3;
genome.erase(0, endGene);
cout << genome;
}
}
return 0;
}
The code itself runs fine, it displays "No gene is found" correctly and doesn't stick me in a loop of not closing.
However, the string I'm being asked to test it with (TTATGTTTTAAGGATGGGGCGTTAGTT), does not output the correct results.
Whenever I input the string I get the following:
TTT
GGATGGGGCGTTAGTTGGGCGT
TT
When I should be getting:
TTT
GGGGCGT
I feel like I'm missing something very simple, any help would be appreciated.

Why do I get a vector subscript out of range error here?

i am creating a somekind of rpg battle, where the program reads the input from a .txt file. i created the code but when i want to start the battle, it gave me an error vector subscript out of range. can anyone help me how to fix this? thank you very much :) here is the code. I included everything just so you could get a full context but the main problem I believe is in my while loop in the main cpp, if you want to just skip down to there.
and so that we are on the same track, the content of the txt file for lamanite(hitpoints and regen points) is
8 2
7 3
6 1
for nephite its
10 3
12 4
11 5
here is my warrior.h file
#pragma once
#include <string>
using namespace std;
class warrior
{
public:
warrior ();
warrior (int h, int r);
int getDamage() const;
void takeDamage(int damage);
int getCurrentHP() const;
void regenerate();
string tostring(int h, int r);
private:
int HitPoints;
int RegPoints;
int damage;
};
here is my warrior cpp
#include "warrior.h"
#include <string>
#include <iostream>
warrior::warrior(int h, int r)
{
HitPoints = h;
RegPoints = r;
}
int warrior::getDamage() const
{
int damage = rand () % HitPoints;
return damage;
}
void warrior::takeDamage(int damage)
{
HitPoints = HitPoints - damage;
}
int warrior::getCurrentHP() const
{
return HitPoints;
}
void warrior::regenerate()
{
HitPoints = HitPoints + rand () % (RegPoints);
}
string warrior::tostring(int h, int r)
{
return 0;
}
my main file
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <ctime>
#include "warrior.h"
using namespace std;
void main ()
{
srand(time(0));
ifstream input1;
cout << "input file name nephite: ";
string filename;
cin >> filename;
input1.open(filename);
int HP1, RP1;
vector <warrior*> nephites;
while (input1 >> HP1 >> RP1)
{
nephites.push_back(new warrior(HP1, RP1));
}
cout << nephites.size() << endl;
ifstream input2;
cout << "input file name lamanite : ";
string filename2;
cin >> filename2;
input2.open(filename2);
int HP2, RP2;
vector <warrior*> lamanites;
while (input2 >> HP2 >> RP2)
{
lamanites.push_back(new warrior(HP2, RP2));
}
cout << lamanites.size() << endl;
cout << endl << "Battle" << endl;
warrior nephitesw = warrior (HP1,RP1);
warrior lamanitesw = warrior (HP2,RP2);
while ((nephites.size() > 0) && (lamanites.size() > 0))
{
int rN = rand () % nephites.size();
int rL = rand () % lamanites.size();
cout << rN << "xx" << rL << endl; // so that i know what rN and rL is
while((nephites[rN]->getCurrentHP() > 0) && (lamanites[rL]->getCurrentHP() > 0)) // the program can't execute this part of the code
{
nephites[rN]->takeDamage(lamanites[rL]->getDamage());
lamanites[rL]->takeDamage(nephites[rN]->getDamage());
if(lamanites[rL]->getCurrentHP() > 0)
{
lamanites[rL]->regenerate();
}
else
{
lamanites.erase(lamanites.begin() + (rL));
}
if(nephites[rN]->getCurrentHP() > 0)
{
nephites[rN]->regenerate();
}
else
{
nephites.erase(nephites.begin() + (rN));
}
}
cout << "NEP HP: " << nephites[rN]->getCurrentHP() << " " << "LAM HP: " << lamanites[rL]->getCurrentHP() << endl;
}
system ("Pause");
}
You have a while loop that tests for a certain properties of nephites[rN] and lamanites[rL]:
while((nephites[rN]->getCurrentHP() > 0) && (lamanites[rL]->getCurrentHP() > 0)
{
// ...
}
But inside that loop you might erase those elements:
{lamanites.erase(lamanites.begin() + (rL));}
// ...
{nephites.erase(nephites.begin() + (rN));}
At the very least, after one of those erase operations you'll be testing a different nephite or lamanite object on the next loop iteration (which may or may not be what you want), but if you've erased the last element in the container, you have the problem that the index is now out of range.
You are looping until either nephites[rN]->getCurrentHP() <= 0 or lamanites[rL]->getCurrentHP() <= 0. However, whichever one drops to 0 first will be deleted from the vector:
// ...
{lamanites.erase(lamanites.begin() + (rL));}
// ...
{nephites.erase(nephites.begin() + (rN));}
If rN == nephites.size() or rN == lamanites.size() (which will definitely happen when the size is 1 and may randomly happen earlier), this will cause you to index out of the vector when you test the loop.
To quickly solve the problem, move the code that removes the warrior(s) from the vector out of the loop:
while((nephites[rN]->getCurrentHP() > 0) && (lamanites[rL]->getCurrentHP() > 0))
{
nephites[rN]->takeDamage(lamanites[rL]->getDamage());
lamanites[rL]->takeDamage(nephites[rN]->getDamage());
if(lamanites[rL]->getCurrentHP() > 0)
{
lamanites[rL]->regenerate();
}
if(nephites[rN]->getCurrentHP() > 0)
{
nephites[rN]->regenerate();
}
}
cout << "NEP HP: " << nephites[rN]->getCurrentHP() << " " << "LAM HP: " << lamanites[rL]->getCurrentHP() << endl;
// *****
// Move the erasures out of the loop
// *****
if(lamanites[rL]->getCurrentHP() <= 0)
{
lamanites.erase(lamanites.begin() + (rL));
}
if(nephites[rN]->getCurrentHP() <= 0)
{
nephites.erase(nephites.begin() + (rN));
}