C++ extraneous for loop needed for program to run successfully - c++

Before we start, yes this is homework, no i'm not trying to get someone else to do my homework. I was given a problem to have someone enter a binary number of up to 7 digits and simply change that number from binary to decimal. Though i'm most certainly not using the most efficient/best method, i'm sure I can make it work. Lets look at the code:
#include <iostream>
#include <math.h>
using namespace std;
int main() {
char numbers[8];
int number = 0, error = 0;
cout << "Please input a binary number (up to 7 digits)\nBinary: ";
cin.get(numbers, 8);
cin.ignore(80, '\n');
for (int z = 7; z >= 0; z--){}
cout << "\n";
for (int i = 0, x = 7; x >= 0; x--, i++){
if (numbers[x] <= 0){ // if that is an empty space in the array.
i--;
}
else if (numbers[x] == '1'){
number += pow(2, i);
}
else if (numbers[x] != '0'){ // if something other than a 0, 1, or empty space is in the array.
error = 1;
x = -1;
}
}
if (error){ // if a char other than 0 or 1 was input this should print.
cout << "That isn't a binary number.\n";
}
else{
cout << numbers << " is " << number << " in decimal.\n";
}
return 0;
}
If I run this code it works perfectly. However in a quick look through the code there is this "for (int z = 7; z >= 0; z--){}" which appears to do absolutely nothing. However if I delete or comment it out my program decides that any input is not a binary number. If someone could tell me why this loop is needed and/or how to remove it, it would be much appreciated. Thanks :)

In your loop here:
for (int i = 0, x = 7; x >= 0; x--, i++){
if (numbers[x] <= 0){ // reads numbers[7] the first time around, but
// what if numbers[7] hasn't been set?
i--;
}
you are potentially reading an uninitialized value if the input was less than seven characters long. This is because the numbers array is uninitialized, and cin.get only puts a null terminator after the last character in the string, not for the entire rest of the array. One simple way to fix it is to initialize your array:
char numbers[8] = {};
As to why the extraneous loop fixes it -- reading an uninitialized value is undefined behavior, which means there are no guarantees about what the program will do.

Related

How do i make my array compare and then display certain outputs based on users guess

Newer to coding and im stuck, Need to make a array thats stores 5 numbers (1-9), then i need to check that array for duplicates if there is duplicates i need to replace that number either with a whole new random line no duplicates (seems like the easier option) or just replace that one number,
after that wants me to get users 5 numbers guess store that in a array, display that array at the bottom along with these under each of the numbers
// The * = means the number is in the exact location
// The - = means the array does not contain that number
// The + = means the array contains the number but its not in the right location
All the arrays want the digits to be entered one at a time
repeat steps till user gets all the numbers to * then end game with completion msg.
My true problem lies with step 4 and step 7;
Below is the code ive been working on today but any help would be truly appreciated
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void game_instructions(int n);
bool search_array(int a[], int n, int t);
int main()
{
//Step 1: Declare your variables and constants
const int SIZE = 5; //this constant stores the length/size of the code
int randcode[SIZE]; //this array stores the code generated randomly by the computer
int guess[SIZE]; //this array stores the code inputted by the player/user
//you may add more variables as needed
//Step 2: Output game instructions by calling function game_instructions
game_instructions(SIZE);
//Step 3: Generate a random code and store it in the array randcode one digit at a time.
//Each digit should be between 0 and 9 and should be stored as one array element
//Recall that rand() % 10 can be used to generate a number between 0 and 9
srand(time(0));
for(int i=0;i<SIZE;i++)
randcode[i]= (rand() % 10); //Computers random 5 numbers generated
cout<<"\nRandom C-numbers::"<<endl;
for(int i=0;i<SIZE;i++)
cout<<randcode[i] << " ";
//Step 4: Repeat step 3 if the array randcode contains duplicates
//You must use function contains_duplicates to implement this step
//Step 5: Ask the user for his guess and store it in the array guess.
//Read one digit at a time, validate it to make sure it is between 0 and 9, and store it as one array element
for (int i=0; i<SIZE; i++) {
cout<<"\nEnter Digit "<< i+1 << ": ";
cin >> guess[i];}
cout << endl;
//Step 6: Output the array guess on a single line with a space after each element (see the sample output provided)
for (int n=0; n < SIZE; ++n) {
cout << guess[n] << " ";
}
//Step 7: Compare the randomly generated code (randcode) with the user's guess (guess)
//and display feedback for each digit as: *, + or –, as explained below:
//For each digit in the user's guess do the following:
// If it matches the digit from the random code (both value and position), output *
// Otherwise, if it appears anywhere in the random code, output + (use function search_array here)
// Otherwise, output -
//Step 8: Repeat steps 5,6,7 until all digits have been guessed correctly
//Step 9: Output congratulations message
cout << endl << endl;
cout << "Good job! You guessed the code!";
return 0;
}
void game_instructions(int n)
//This function outputs the game instructions.
//Its parameter n represents the length of the code.
{
cout << "A random " << n << " digit code has been generated. You have to guess it. \n";
cout << "For every digit you will receive feedback in the form of *, + or - \n";
cout << " * means the digit is in the code and it is in the correct position.\n";
cout << " + means the digit is in the code but it is not in the correct position.\n";
cout << " - means the digit is not in the code.\n";
}
bool search_array(int a[], int n, int t)
//This function searches the array a (of size n) for a target value t.
//If t is found in the array the function returns true; otherwise it returns false.
{
for (int i = 0; i < n; i++)
{
if (a[i] == t) return true;
}
return false;
}
bool contains_duplicates(int a[], int n)
//This function searches the array a (of size n) and returns true if the array contains duplicates; otherwise, it returns false.
{
for (int i = 0; i < n; i++)
{
//compare element a[i] with all the remaining elements from index i+1 to n
for (int j = i+1; j < n; j++)
{
if (a[i] == a[j]) return true;
}
}
return false;
}
I got most the side code done but im just stumped on how to get this array to match any help would be nice
Here is how I would implement the program to generate the number without duplicate:
Step3 would look like this:
int tempNumber;
int i = 0;
while (i < SIZE) {
tempNumber = (rand() % 10);
if (contains_duplicates(randcode, tempNumber, i) == false) {
// every time there is no duplicate we push and add i by 1;
randcode[i] = tempNumber; // Computers random 5 numbers generated
i++;
}
}
contains_duplicates function would look like this:
bool contains_duplicates(int arr[], int tempNum, int currentArrSize)
// This function searches the array a (of size n) and returns true if the
//array
// contains duplicates; otherwise, it returns false.
{
for (int j = 0; j <= currentArrSize; j++) {
// if the array[index] not equal generated number the loop will
//iterate again without going to the line below
if (arr[j] != tempNum) {
continue;
}
// if the array[index] equal the function will return true and end
//the function
// uncomment this to check how many time it duplicate (not
//necessary tho)
//cout << "if return true, this will appear"<< endl;
return true;
}
// if the loop is done and no duplicate, function will return false
return false;
}
With this method it is not necessary to do step 4 because we already prevent duplicate array!
Here is the last problem from your question which is step 7:
cout << endl;
for (int i = 0; i < SIZE; i++) {
if (guess[i] == randcode[i]) {
cout << "* ";
} else if (search_array(randcode, SIZE, guess[i])) {
cout << "+ ";
} else {
cout << "- ";
}
}
Seems like the problem has been solved, now try to implement step 8 by yourself, good luck :)

A program to find out if a word is palindrome

Written some algorithm to find out if a given word is a palindrome. But one of my variables (counter) seems not updating when I debugged and I can't figure out what is wrong with it. I may be wrong though... any help will be needed as I don's wanna copy some code online blindly.
Below is the code:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
//take input
string input;
cout << "Enter your word: ";
cin >> input;
//initialize arrays and variables
int counter = 0, k = 0;
int char_length = input.length();
char characters[char_length];
strcpy(characters, input.c_str());//copy the string into char array
//index of character at the midpoint of the character array
int middle = (char_length-1)/2;
int booleans[middle]; //to keep 1's and 0's
//check the characters
int m = 0, n = char_length-1;
while(m < middle && n > middle){
if(characters[m] == characters[n]){
booleans[k] = 1;
} else {
booleans[k] = 0;
}
k++;
m++;
n--;
}
//count number of 1's (true for being equal) in the booleans array
for(int i = 0; i < sizeof(booleans)/sizeof(booleans[0])-1; i++){
counter += booleans[i];
}
//compare 1's with size of array
if(counter == middle){
cout << input << " is a Palindrome!" << endl;
} else {
cout << input << " is not a Palindrome!" << endl;
}
return 0;
}
Brother it seems difficult to understand what your question is and what code you are typing. I am not very much experienced but according to me palindrome is a very very simple and easy program and i would have wrote it as:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char str1[20], str2[20];
int i, j, len = 0, flag = 0;
cout << "Enter the string : ";
gets(str1);
len = strlen(str1) - 1;
for (i = len, j = 0; i >= 0 ; i--, j++)
str2[j] = str1[i];
if (strcmp(str1, str2))
flag = 1;
if (flag == 1)
cout << str1 << " is not a palindrome";
else
cout << str1 << " is a palindrome";
return 0;
}
It will work in every case you can try.
If you get a mismatch i.e. (characters[m] == characters[n]) is false then you do not have a palindrome. You can break the loop at that point, returning false as your result. You do not do that, instead you carry on testing when the result is already known. I would do something like:
// Check the characters.
int lo = 0;
int hi = char_length - 1;
int result = true; // Prefer "true" to 1 for better readability.
while (lo < hi) { // Loop terminates when lo and hi meet or cross.
if(characters[lo] != characters[hi]) {
// Mismatched characters so not a palindrome.
result = false;
break;
}
lo++;
hi--;
}
I have made a few stylistic improvements as well as cleaning up the logic. You were doing too much work to solve the problem.
As an aside, you do not need to check when the two pointers lo and hi are equal, because then they are both pointing to the middle character of a word with an odd number of letters. Since that character must be equal to itself there is not need to test. Hence the < in the loop condition rather than <=.
Existing Code does not work for Palindromes of Odd Length because of
for(int i = 0; i < sizeof(booleans)/sizeof(booleans[0])-1; i++)
Either use i<=sizeof(booleans)/sizeof(booleans[0])-1; or i<sizeof(booleans)/sizeof(booleans[0]);.
Currently, you are not counting the comparison of character[middle-1] and character[middle+1].
For palindromes of even length, you will have to change your logic a bit because even length palindromes don't have a defined middle point.
#include <iostream>
#include <cstring>
using namespace std;
int main(){
//take input
string input;
cout << "Enter your word: ";
cin >> input;
//initialize arrays and variables
int counter = 0, k = 0;
int char_length = input.length();
char characters[char_length];
strcpy(characters, input.c_str());//copy the string into char array
//index of character at the midpoint of the character array
int middle = (char_length+1)/2;
int booleans[middle]; //to keep 1's and 0's
//check the characters
int m = 0, n = char_length-1;
while(m<=n){
if(characters[m] == characters[n]){
booleans[k] = 1;
} else {
booleans[k] = 0;
}
k++;
m++;
n--;
}
//count number of 1's (true for being equal) in the booleans array
for(int i = 0; i < sizeof(booleans)/sizeof(booleans[0]); i++){
counter += booleans[i];
}
cout<<counter<<" "<<middle<<endl;
//compare 1's with size of array
if(counter == middle){
cout << input << " is a Palindrome!" << endl;
} else {
cout << input << " is not a Palindrome!" << endl;
}
return 0;
}
Over here the size of the boolean array is (length+1)/2,
For string s like abcba it will be of length 3.
This corresponds to a comparison between a a, b b and c c. Since the middle element is the same, the condition is always true for that case.
Moreover, the concept of middle is removed and the pointers are asked to move until they cross each other.

Counting occurences of same array value in C++

I recently have been building a program where:
A user is asked to enter a number that will represent the size of a character array.
Then they are asked whether they will want the program to fill the values automatically, or they could press M so they could enter the values manually. They may only enter a-zA-Z values, or they will see an error.
At the end of the program, I am required to count every duplicate value and display it, for example:
An array of 5 characters consists of A;A;A;F;G;
The output should be something like:
A - 3
F - 1
G - 1
I could do this easily, however, the teacher said I may not use an additional array, but I could make a good use of a few more variables and I also can't use a switch element. I'm totally lost and I can't find a solution. I've added the code down below. I have done everything, but the counting part.
#pragma hdrstop
#pragma argsused
#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
void main() {
int n, i = 0;
char masiva_izvele, array[100], masiva_burts;
cout << "Enter array size: ";
cin >> n;
clrscr();
cout << "You chose an array of size " << n << endl;
cout << "\nPress M to enter array values manually\nPress A so the program could do it for you.\n\n";
cout << "Your choice (M/A): ";
cin >> masiva_izvele;
if (masiva_izvele == 'M' || masiva_izvele == 'm') {
clrscr();
for (i = 0; i < n; i++) {
do {
cout << "Enter " << i + 1 << " array element: ";
flushall();
cin >> masiva_burts;
cout << endl << int(masiva_burts);
if (isalpha(masiva_burts)) {
clrscr();
array[i] = masiva_burts;
}
else {
clrscr();
cout << "Unacceptable value, please enter a value from the alphabet!\n\n";
}
}
while (!isalpha(masiva_burts));
}
}
else if (masiva_izvele == 'A' || masiva_izvele == 'a') {
clrscr();
for (i = 0; i < n; i++) {
array[i] = rand() % 25 + 65;
}
}
clrscr();
cout << "Masivs ir izveidots! \nArray size is " << n <<
"\nArray consists of following elements:\n\n";
for (i = 0; i < n; i++) {
cout << array[i] << "\t";
}
cout << "\n\nPress any key to view the amount of every element in array.";
//The whole thing I miss goes here, teacher said I would need two for loops but I can't seem to find the solution.
getch();
}
I would be very thankful for a solution so I could move on and forgive my C++ amateur-ness as I've picked this language up just a few days ago.
Thanks.
EDIT: Edited title to suit the actual problem, as suggested in comments.
One possible way is to sort the array, and then iterate over it counting the current letter. When the letter changes (for example from 'A' to 'F' as in your example) print the letter and the count. Reset the counter and continue counting the next character.
The main loop should run foreach character in your string.
The secondary loop should run each time the main "passes by" to check if the current letter is in array. If it's there, then ++.
Add the array char chars[52] and count chars in this array. Then print out chars corresponding to the array, which count is more than 1.
std::unordered_map<char, int> chars;
...
char c = ...;
if ('A' <= c && c <= 'Z')
++chars[c];
else if ('a' <= c && c <= 'z')
++chars[c];
else
// unexpected char
...
for (const auto p : chars)
std::cout << p.first << ": " << p.second << " ";
Assuming upper and lower case letters are considered to be equal (otherwise, you need an array twice the size as the one proposed:
std::array<unsigned int, 26> counts; //!!!
// get number of characters to read
for(unsigned int i = 0; i < charactersToRead; ++i)
{
char c; // get a random value or read from console
// range check, calculate value in range [0; 25] from letter...
// now the trick: just do not store the value in an array,
// evaluate it d i r e c t l y instead:
++counts[c];
}
// no a d d i t i o n a l array so far...
char c = 'a';
for(auto n : counts)
{
if(n > 0) // this can happen now...
{
// output c and n appropriately!
}
++c; // only works on character sets without gaps in between [a; z]!
// special handling required if upper and lower case not considered equal!
}
Side note: (see CiaPan's comment to the question): If only true duplicates to be counted, must be if(n > 1) within last loop!

Vector: range error at memory

I have been programming a bit with C++ in CodeBloks before and since some time i started to program in MS Studio. At the moment im programming a little game from the book: Programming: Principles and Practice using C++. Exercise 12 of chapter 5.
I have been looking around on the internet to fix the range memory error which keeps occuring whatever I try (see printscreen link).
The description about the program is in the code itself.
I also did make the vectors a hard coded (if I say that right) size to make the program stop complaining about their memory range errors.
Note: Yes this is a school exercise/practice as well. But I rather ask what I did wrong then copy paste the code from the internet..
Please look over my code and see or I made some mistake with me vectors, cause that is where my errors are probably comming from.
Update: placed as answer in this topic.
Link to update
Error:
Unhandled exception at 0x7529CBC2 in Tweede project.exe: Microsoft C++ exception: Range_error at memory location 0x006FF510.
Program:
#include "std_lib_facilities.h"
int main(){
bool while_bit = false;
vector<int>bulls_cows(4);
vector<int>inputs_arr(4);
//Generate 4 random numbers.
for (int a = 0; a < 4; ++a){
bulls_cows[a] = a + 1;//randint(a) % 9 + 0; //random number between 0 and 9.
}
//bulls_cows[1] = randint(10);
cout << "For this game, called Bulls and Cows, you have to guess the four right numbers between 0 and 9.\n";
cout << "When one or more digets are right and in the right position the program will say the number of Bulls.\n";
cout << "When one or more digets are right but not in the right position the program will say the number of Cows.\n";
cout << "Please enter 4 number by filling in ONE positive diget and press enter. Do this four times and wait for the result.\n";
for (int z = 0; z < 4; ++z) {
cout << bulls_cows[z] << "\n";
}
while (while_bit == false) {
int input = 0; //Reset of input, cows and bulls every round.
int cows = 0;
int bulls = 0;
cin >> input;
//Test for legit input. If legit then it writes it to the array called "input_arr"
if (input < 0 || input > 9) {
cout << "Number must be between 0 and 9.\n";
}
else {
inputs_arr.push_back(input);
}
//Check or 4 numbers have been given.
if (sizeof(inputs_arr) < 4) {
//Check for equal numbers on same spot.
for (int b = 0; b < 4; ++b) {
if (inputs_arr[b] == bulls_cows[b]) {
bulls + 1;
}
}
//Check for a number in all spots.
for (int c = 0; c < 4; ++c) {
if (inputs_arr[c] == bulls_cows[0] || bulls_cows[1] || bulls_cows[2] || bulls_cows[3]) {
cows +1;
}
}
}
if (bulls < 4) {
cout << "You did not guess the right combination.\n";
cout << "Number of bulls: " << bulls << "\n";
cout << "Number of cows: " << cows << "\n";
inputs_arr[0, 0, 0, 0]; //Empty array.
}
if (bulls == 4) {
cout << "You guessed the right combination!\n";
while_bit = true;
}
}
keep_window_open(); //To keep terminal open since MS Studio doesn't itself.
return 0;
}
Using the sizeof operator with your inputs_array vector will give you the size in bytes of that object in memory. Perhaps you've used this with arrays before.
Instead, I think you want the number of items you've pushed into the vector. std::vector has a function called size which gives the number of items pushed to it.
In Visual Studio you should really, really set up the warning level to level 4. Then the compiler will tell you about several of the odd things you try to do.
For example:
warning C4552: '+': operator has no effect; expected operator with side-effect 1>
bulls + 1;
You compute a result, but never store it anywhere. Same thing for the cows.
error C4548: expression before comma has no effect; expected expression with side-effect
inputs_arr[0, 0, 0, 0]; //Empty array.
This is not the way to empty an array. To remove all elements, you do inputs_arr.clear();.
warning C4127: conditional expression is constant
if (sizeof(inputs_arr) < 4) {
Like we have already seen, sizeof is the size of the vector object (always the same), not the number of elements it holds.
Then there are some logic errors.
vector<int>inputs_arr(4);
This creates a vector originally holding 4 ints.
But later when you do
inputs_arr.push_back(input);
it adds more elements to the vector, so now it might hold up to 8 ints. You have to decide if you want to create it with the full size up front, or add elements as you go along. But not both.
Another problem is with the condition
if (inputs_arr[c] == bulls_cows[0] || bulls_cows[1] || bulls_cows[2] || bulls_cows[3]) {
Even though there are languages where you can write conditions similar to this, in C++ you cannot. To compare a variable x to several other values, you have to spell it out:
if (x == y || x == z || x == w)
Update: (wasn't sure or I had to add it to the question or as answer. If wrong, please let me know. Im new to Stack overflow ;) )
It seems some statement/loop brackets where not placed right. I edit that and a bit:
Sadly it seems that my intergers cows and bulls do not reset at line 61 and 62.. Anyone a idea what I might have done wrong there.
LOG:
cin did not not loop. Also edited else-statement 'inputs_arr.pushback(input)' and added all for-loops and statements below it. Fixed a part of the cin problem.
Replaced bulls, cows and input integers to top of program, and the reset at the end of the false/if-statement.
Put all loops and statements below the if-statement '(int b = 0; b < 4; ++b)' into it.
Edited the for-loop to >4 which couts "Size of array" to see what values it has. Gets deleted later on cause it is for test only.
#include "std_lib_facilities.h"
int main()
{
bool while_bit = false;
int input = 0;
int cows = 0;
int bulls = 0;
vector<int> bulls_cows(4); //size needed to prevent memory size error at line 11.
vector<int> inputs_arr;
//Generate 4 random numbers. Need to add seed later.
for (int a = 0; a < 4; ++a){
bulls_cows[a] = randint(a) % 9 + 0; //random number between 0 and 9.
}
cout << "For this game, called Bulls and Cows, you have to guess the four right numbers between 0 and 9.\n";
cout << "When one or more digets are right and in the right position the program will say the number of Bulls.\n";
cout << "When one or more digets are right but not in the right position the program will say the number of Cows.\n";
cout << "Please enter 4 numbers by filling in ONE positive diget and press enter. Do this four times and wait for the result.\n";
for (int z = 0; z < 4; ++z) { //Gives the generated numbers for testing.
cout << bulls_cows[z] << "\n";
}
while (while_bit == false) {
cin >> input;
//Test for legit input. If legit then it writes it to the array called "input_arr"
if (input < 0 || input > 9) {
cout << "Number must be between 0 and 9.\n";
}
else {
inputs_arr.push_back(input);
//Check or 4 numbers have been given.
if (inputs_arr.size() > 3) {
//Check for equal numbers on same spot.
for (int b = 0; b < 4; ++b) {
if (inputs_arr[b] == bulls_cows[b]) {
++bulls;
}
}
//Check for a number in all spots.
for (int c = 0; c < 4; ++c) {
if (inputs_arr[c] == bulls_cows[0] || inputs_arr[c] == bulls_cows[1] || inputs_arr[c] == bulls_cows[2] || inputs_arr[c] == bulls_cows[3]) {
++cows;
}
}
/*for (int x = 0; x < 4; ++x) { //Couts again the fresh entered numbers for a better overview.
cout << "Size of array: " << inputs_arr[x] << "\n";
}*/
if (bulls < 4) {
cout << "You did not guess the right combination.\n";
cout << "Number of bulls: " << bulls << "\n";
cout << "Number of cows: " << cows << "\n";
int cows = 0; //Reset of cows and bulls each round.
int bulls = 0;
inputs_arr.clear(); //Empty the array.
cout << "Please enter 4 numbers:\n";
}
if (bulls == 4) {
cout << "You guessed the right combination!\n";
while_bit = true;
}
}
}
}
keep_window_open(); //To keep terminal open since MS Studio doesn't itself.
return 0;
}

C-string assignment using for loop

I think this is a relevant topic, while browsing this forum and tutorial I have tweaked my c-string to the proper format(I think) but there's just one topic missing. How can we take an integer, using a for loop, and assign the c-string values from the integer.
I'm just focusing on the integer to binary part right now and I'm sure my number manipulation is solid. However, my prof said we needed to assign the binary values to a c-string. And I'm trying this, it's telling me I'm using a const char and a char* via the compiler. I'm not sure how this is happening, or how to prevent it.
Here's my source code:
//sample integer to binary
#include <iomanip>
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main()
{
int num; //the number a user enters
int rem; //the remainder, the 1 and 0 of the binary number
int x; //a variable to store the number after division
char binary[10]; //c-string initialized to 10, perhaps that is too many.
cout << "Enter a number: ";
cin >> num;
for (int i = 0; i < 10; i++)
{
x = num / 2;
cout << x << endl; //this shows that the code is working
rem = num % 2;
cout << num << endl; //this also shows the code is working
char r = (char)rem; //These two lines of code are
strcpy(binary[i], r); //preventing compilation
cout << binary[i] << endl; // this is diagnostic
num = x;
}
cout << "The number " << num << " is " << binary[5] << " in binary.\n";
return 0;
}
Thanks you two, I've been able to make this work (almost).
I'm still getting some unexpected behavior, and I'm not sure how big to initialize the array to, I don't think that it would matter too much, but I don't know exactly how big of numbers the graders use to test.
Anyways, here's the new code:
#include <iomanip>
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main()
{
int num; //the number a user enters
int rem; //the remainder, the 1 and 0 of the binary number
int x; //a variable to store the number after division
char binary[5] = {'0', '\0'}; //c-string initialized to 10, perhaps that is too many.
cout << "Enter a number: ";
cin >> num;
for (int i = 0; i < 10; i++)
{
x = num / 2;
//cout << x << endl; //this shows that the code is working
rem = num % 2;
//cout << num << endl; //also shows the code is working
binary[i] = '0' + rem; //not sure what this is doing, but it works.
//cout << binary[i] << endl; // this is diagnostic
num = x;
}
cout << "The number " << num << " is " << binary << " in binary.\n";
return 0;
}
And here's the output:
Enter a number: 5
The number 0 is 1010000000# in binary.
It should show the number, the initial number, and say 101, without the 0's and the # sign.
strcpy is for copying entire NUL-terminated string. If you want to set just one character, you can use =.
binary[i] = r;
However, if you want the line cout << binary[i] to work right, or to treat binary as a C string later, you need to store ASCII digits:
binary[i] = '0' + r;
Don't forget to add a terminating NUL to your string, right now it isn't a C-style string at all.
The arguments to strcpy() are char*, not char. The second argument must point to a null-terminated string, but r is just a single character. To assign a character to an element of an array, do:
binary[i] = r;
But you don't want the binary value of rem, you want the character that represents that binary value. It should be:
char r = '0' + rem;
In order to print binary as a string, you need to give it a null terminator. Since you're putting 10 digits into the string, you need to declare an extra character to hold the terminator, and initialize it with zeroes so it will be terminated properly.
char binary[11] = {0};
And if you want to print the whole string, you shouldn't reference binary[5], you should print the whole array:
cout << "The number " << num << " is " << binary << " in binary.\n";
In addition to problems already pointed out, you get binary digits in the reverse order. You have to count significant digits in your binary representation and reverse characters when you're done.
You didn't initialize the character buffer correctly that's why you are getting garbage in the print out.
As for the buffer size, you need as many characters as there are bits in the integer type you are converting plus one more for the terminating '\0', so for a 32-bit number you need 33 character size buffer. And that's important because if you overrun your buffer, quite nasty things will happen.
And one more note: I assume that numbers you are supposed to convert to a string representation are unsigned, so be explicit about it. Below is a quick and dirty implementation with some minimal error checking:
char *unsigned_to_binstr (unsigned n, char *binary, int buf_len)
{
int i, j;
if (buf_len < 2)
return NULL;
i = 0;
do {
binary[i++] = '0' + n % 2;
n /= 2;
} while (n && i < buf_len);
for (j = 0; j < i / 2; ++j) {
char temp = binary[j];
binary[j] = binary[i-j-1];
binary[i-j-1] = temp;
}
binary[i] = '\0';
return binary;
}
After everyone's comments, and my own research via my textbook I was able to formulate a somewhat working function. However, in the process I began to wonder about the garbage problem, so my solution.. Truncate! I added if clauses (tried to think of a loop representation but didn't get any ideas) and at the end I just use the length provided via if clauses and subtract 1, which should give me the appropriate bit size for the number. Using what basic c++ knowledge we've covered in class this is the solution I came up with, however crude and inefficient it might be!
I want to thank all of you, I couldn't have gotten past the point I was stuck at if it weren't for you!
Here's my rough final revision:
//sample integer to binary
#include <iostream>
using namespace std;
int main()
{
int num; //the number a user enters
int rem; //the remainder, the 1 and 0 of the binary number
int x; //a variable to store the number after division
int l; //length of c-string function
cout << "Enter a number: ";
cin >> num; //user input
if ((num == 1) || (num == 0)) // the following 17 lines of code are to truncate the string size.
l = 2;
if ((num > 1) && (num < 4))
l = 3;
if ((num >= 4) && (num <= 7))
l = 4;
if ((num >= 8) && (num <= 15))
l = 5;
if ((num >= 16) && (num <= 31))
l = 6;
if ((num >= 32) && (num <= 63))
l = 7;
if ((num >= 64) && (num <= 127))
l = 8;
if ((num >= 128) && (num <= 255))
l = 9;
if ((num > 255))
cout << "This number is too large for this string\n"; // I don't think the binary sequence should be larger than 16 bits.
char binary[l]; //c-string initialized to size according to the truncation rules above
for (int i = l - 1; i > 0; i--) //goes in reverse order, as binary counts from bottom to top.
{
x = num / 2;
rem = num % 2;
num = x;
binary[i] = '0' + rem; // added an
}
for (int i = 0; i <= l-1; i++)
{
cout << binary[i];
}
cout << " in binary.\n";
return 0;
}