Minor sequence error in C++ program output - c++

I am trying to output "states" for any binary number that is inserted (for each 0 it outputs a random number between 1 & max), for example 10100 should output 2, random number between 1 & 2, 3, random number between 1 & 3, random number between 1 & 3. Thus looking like 21323 or 223212 or 21313, etc. But the output my program is giving me is 23456 - why?
int main()
{
char binaryArray [0];
int c1=1;
int c0=0;
int i=0;
int n;
cout << "Enter length of binary: "; //Length = total number of 1s & 0s
cin >> n;
cout << "Enter binary number: ";
cin >> binaryArray;
cout << "States: ";
for(i; i<n; i++)
{
if(binaryArray[i]=1)
{
c1++;
cout << c1;
}
else if(binaryArray[i]=0)
{
c0++;
cout << rand()%c1+1;
}
/* if(c0 > c1)
{
cout << "Invalid Binary Representation.\n" << endl;
exit(0);
} */
}
system("PAUSE");
return 0;
}

When you have an array of 0 (that is: zero) characters, you cannot save anything in it, not even a single bit. Make that array "large enough" (whatever that means for you) or better use a std::string instead.
Oh, and compile your code with all compiler warnings enabled. When you have understood and fixed all these warnings properly, you program should work much better. (Hint: assignment inside conditional)

First of all, you have assignment in the if statements. Use == instead of =.
Second, if you expect the number to be entered as binary and stored in char array, use char when comparing. So, your if statements should be:
// vvvvvvv
if( binaryArray[i] == '1' )
{
c1++;
cout << c1;
}
// vvvvvvv
else if( binaryArray[i] == '0' )
{
c0++;
cout << rand()%c1+1;
}
Third, change the size of your array:
char binaryArray [0];
It must not be 0 here. Change it so something more common. Like 512, for example, if you think that this will be big enough.

Related

Random data loss in array c++

Here's my problem.... In the code below, between the char guess[4] and cin >> guess my answer's element at index 0 disappeared. Anyone knows why?
while(bullCount != 4)
{
//Create the answer
char answer[4];
for(int loops = 0; loops < 4; loops++)
{
answer[loops] = createAnswerDigit(seed);
}
//Reset bullCount and cowCount from previous loop
bullCount = 0;
cowCount = 0;
cout << "Enter your guess [1000-9999]: ";
//Guess by player
char guess[4];
cout << "Answer[0]: " << answer[0] << "\n"; //Prints "Answer[0]: 4
//Retrieve guess by player
cin >> guess;
cout << "Answer[0]: " << answer[0] << "\n" //Prints "Answer[0]: "
for(int digitLoc = 3; digitLoc >= 0; digitLoc--)
{
//Do check backwards to prevent mistaking bulls for cows
int check = checkGuess(guess[digitLoc], digitLoc, answer);
if(check == cow)
{
cowCount++;
}
else if(check == bull)
{
bullCount++;
}
}
}
guess has a size of 4, however, you enter a number between 1000 - 9999 which is 4 characters long. Remember that in a string, there must be a \0 at the end of the string, so guess is 1 character short. This might be overwriting the first element of answer. Try making guess of size 5, or better yet, use std::string instead.
Clearly, the guess is an array of 4 chars. Whenever the user enters characters in range 1000-9999 it doesn't have a space for the string terminator '\0'. Thus, you need to define the array as:
char guess[5];
or you can use string implementations too

Addition and subtraction of arrays

I have been working on this all day but just cant get the output right.
What I want to do is input two numbers, which would be pushed into two arrays so we can subtract or add them and display the result. Seems simple, but there are few catches
Input must be pushed into the array, from the user, one by one.
In case I don't enter a value, code should assume it to be '0' or 'null'. '0' if its in the beginning and 'null' if its in the end. for example if 1st number is 234 and second number is 23 then code should make it into '023' and if I enter first number as 2, 2nd number as 3 but don't enter anything in the end then code should assume it to be null.
Problems
I cant take 'carry' to the next set, in case the sum is greater than 10. Which means the value I m getting is just addition of two numbers doesn't matter if its greater than 10 or not. for example addition of 234 and 890 is giving me [10, 12, 4]
Here is the code.....
#include<iostream>
using namespace std;
main() {
int first[10], second[10], result[10], c, n;
cout << "Enter the number of elements in the array ";
cin >> n;
if (n > 10 || n < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
cout << "Enter elements of first array " << endl;
for (c = 0; c < n; c++) {
cin >> first[c];
if (first[c] > 9 || first[c] < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
}
cout << "Enter elements of second array " << endl;
for (c = 0; c < n; c++)
cin >> second[c];
cout << "Sum of elements of two arrays " << endl;
for (c = 0; c < n; c++)
cout << first[c] + second[c] << endl;
if ((first[c] + second[c]) > 9) {
cout << "overflow" << endl;
}
//result[c] = first[c] + second [c];
//cout << result[c] <<endl;
system("PAUSE");
return 0;
}
I would really appreciate some suggestions.
In case your intention is to have the result of e.g.
234 + 890 = 1124
then your summation loop should be in reverse order.
(Since you are reading number of elements of the array from the prompt, you may use this information to input first/second numbers into each array in the order preferred for the following summation loop.)
For the carry problem, you need to setup a variable and use it in the loop like this, for example.
int sum[10] = {0};
int c;
int carry = 0;
for (c = 0; c < n; c++)
{
sum[c] = first[c] + second[c] + carry;
carry = sum[c] / 10;
}
if (c < n)
sum[c] = carry;
else
cout << "overflow";
Use std::vector and learn how to use reverse iterators. So if someone enters 234 you push_back(2), push_back(3), push_back(4) and have [0]=2,[1]=3,[2]=4. Then if the next number is 23 you have [0]=2,[1]=3. Now walk both vector with reverse iterators so the first call to rbegin() will give a pointer to [2]=4 and the other vector will give [1]=3. Now add and carry using push_back into a third vector to store the result. Output the result using reverse iterators to print the result.
This looks like homework, so no sample code.

Why doesn't my array store any input values?

I want to input any number into array b[] by number of numCase times.
#include <iostream>
using namespace std;
//entry point
int main()
{
//Declarations
int b[20]; // array size 20 ( limit of inputs)
int c = 0;
int numCase;
int input;
cout << "ENTER NUMBER OF CASES (MAXIMUM NUMBER OF 20): \n";
cin >> numCase;
//checks that numCase is less than or equal to (20) and does not exceed
if (numCase < 21)
{
// gets input number based on the numCase
do
{
cout << "ENTER A NUMBER (MAXIMUM OF 5 DIGITS): \n";
cin >> input;
cout << "\n";
b[c] = input;
c++;
} while (c != numCase);
cout << b[c] ; // this is my problem it OUTPUTS RANDOM VALUE,
//but i can see on my watch list that b has the values of my input.
}
}
You're filling entries 0 toN of b, and then printing entry N+1, which you haven't filled in.
The variable c should be initialised back to zero.
} while (c != numCase);
c = 0;
cout << b[c] ; // in this statement c already reached to numCase where you have not assigned any value
I think this is what you might be looking for:
for (int i=0; i<numCase; i++)
{
if(b[i] >= x) //x is a variable that u can set as a limit. eg. 700
{
cout<<"\n"<<b[i];
}
}
Hope it helps
If you want to display all the numbers stored in array b[]
then you may write your code as
for(int i=0;i<=20;i++)
{ if(b[i]<101) //This will exclude all the values which are greater than 101
{cout<<"\n"<<b[i];}}

Stack around the variable is corrupted

I have what seems like a pretty simple, beginner question that I must be missing something obvious. I am just trying to prompt the user to input a 4 digit number and then take in the input as an array, splitting up the digits to be by themselves. I thought it hade something to do with "cin >> input[4]" I just can't seem to get the right answer.
int main()
{
int input[4]; //number entered by user
cout << "Please enter a combination to try for, or 0 for a random value: " << endl;
cin >> input[4];
}
When I go to run it, I get an error message "Stack around the variable was corrupted.
I tried looking at similar examples in other questions but I just can't seem to get it right. I need the input as one 4 digit number and then split it up to a 4 position array.
If anyone could help I would greatly appreciate it.
Your array is of size 4, so elements have indicies 0 .. 3; input[4] is located behind the end of your array so you are attemping to modify memory not allocated or allocated for other stuff.
This will work for you:
cin >> input[0];
cin >> input[1];
cin >> input[2];
cin >> input[3];
You do not need an arry to input 4 digit number.
int in;
int input[4];
cin >> in;
if(in>9999 || in < 1000) {
out << "specify 4 digit number" << endl;
return;
}
input[0] = in%1000;
input[1] = (in-1000*input[0])%100;
input[2] = (in-1000*input[0]-100*input[1])%10;
input[3] = in-1000*input[0]-100*input[1]-input[2]*10;
The problem is that you are trying to read in a character that does not exist (the one at index 4).If you declare input as int input[4];, then it doesn't have any characters at index 4; only indices 0...3 are valid.
Perhaps you should just use an std::string and std::getline(), and you could then parse the user input to integers however you like. Or you can try
std::cin >> input[0] >> input[1] >> input[2] >> input[3];
if you can live with the constraint that the numbers must be whitespace-separated.
This includes a small bit of error checking:
int n = 0;
while( n < 1000 || n >= 10000 ) // check read integer fits desired criteria
{
cout << "enter 4 digit number: ";
cin >> n; // read the input as one integer (likely 10 digit support)
if( !cin.good() ) // check for problems reading the int
cin.clear(); // fix cin to make it useable again
while(cin.get() != '\n'); // make sure entire entered line is read
}
int arr[4]; // holder for desired "broken up" integer
for( int i=0, place=1; i<4; ++i, place *= 10 )
arr[i] = (n / place) % 10; // get n's place for each slot in array.
cout << arr[3] << " " << arr[2] << " " << arr[1] << " " << arr[0] << endl;

Input an integer, get spaced output in C++?

I'm working on homework and I'm stumped on this problem: Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6, [...], output 4000 as
4 0 0 0, and the individual digits of -2345 as 2 3 4 5.
Here's my code so far:
int main()
{
string a; //declares string
cout << "Type an integer: "; //prompts user to input an integer
cin >> a; //stores into string a
cout << "There are " << a.size() << " digits in " << a << endl; //retrieves length of string a
cout << a.at(0);
cout << endl;
system ("pause"); //pauses the system so user can read the screen
return 0; //returns 0 if program works properly
}
Can anyone enlighten me on what I'm doing wrong/what my next step is?
So the steps are..
store the input
display them all one by one separated by spaces
figure out the sum and display that
.
#include<string>
#include<iostream>
using namespace std;
int main()
{
string a;
cout << "Type an integer: ";
// 1. store the input
cin >> a;
// 2. display them all one by one separated by spaces
for(int i=0;i<a.size();++i)
cout << a[i] << ' ';
cout << endl;
// 3. figure out the sum and display that
int total = 0;
for(int i=0;i<a.size();++i)
total += a[i] - '0';
cout << total << endl;
system("pause");
return 0;
}
The tricky part is getting the correct sum in step 3.
total += a[i] - '0';
Lets say for example that a[i] is the character '4'. The ASCII value of character '4' is the integer equivalent of 52, and the ASCII integer equivalent of '0' is 48. Therefore if we take '4' - '0', we will get the difference of 4, which is the integer representation we are looking for in this case.
Here is a simple ASCII chart with character values.
Hope this helps!
You probably want to input the number as a string. This will allow you to do digit by digit processing. Then the user will enter the number once instead of many times as digits.
You could try this piece of code:
int num = 0;
cin>>num;
//Make sure array is large enough to hold all digits
//For an int 10 digits it the max
int digits[10] = {0};
//This variable tracks the count of actual number of
//digits extracted from user input
int digitCount = 0;
while (num > 0)
{
digits[digitCount] = num % 10; //Extract digit at units place
num = num / 10; //Advance through the number
digitCount++;
}
for(int count= digitCount-1 ; count >= 0; count-- )
{
cout<<digits[count]<<" ";
}
Note that the printing loop runs backwards (i.e from digitCount to zero) because the digits are extracted and stored starting from the units place. For a number a like 12345 the digits array will contain 5 4 3 2 1.
Rhonda, I can understand your frustration, computers are like that... they do what you say, not what you mean :-) Hang in there.
You say your program should output each of the digits in the number, yet your program asks the user to enter each of the digits. That is confusing.
Also, you first assign a value to "num" here
cin >> num;
then you overwrite "num" in this line
cin >> num >> a;
I'm not sure what you mean to do here, but what you're telling the computer to do is to read an integer from the input and assign it to "num" and assign the rest to the line to string "a"... if the rest of the line just has a space, the space will be discarded... it acts as a separator. That is probably confusing you as well.
int main()
{
int runningTotal = 0;
std::string inputString;
std::cin >> inputString;
for ( std::string::iterator _it = inputString.begin();
_it != inputString.end(); ++_it )
{
// *_it now represents an individual char of the input string
char a = *_it; char* b = &a;
if ( a != '-' )
{
runningTotal += atoi( std::string( b ).c_str() );
std::cout << *_it << " ";
}
}
std::cout << std::endl << "Total of all digits: " << runningTotal << std::endl;
std::cin.get();
std::system( "pause" );
return 0;
}
I threw this together quickly for you. Hope it's of help.