A variable length bitset in C++ [duplicate] - c++

This question already has answers here:
Define bitset size at initialization?
(7 answers)
Closed 5 years ago.
I have a working 4 bit linear feedback shift register, using 3 bitsets of length 4: inpSeq, operSeq and bit. I want to make the program accept a variable length bit sequence, so those previous bitsets should be of variable length somehow. The user may enter a sequence ofr inpSeq and the program sets the three bitsets to be of the same length as that sequence provided by the user. Any ideas for how to achieve this? Sample code if I may ask!
Here is the code:
#include <iostream> //Standard library.
#include <bitset> //Library for 10 handling.
#include <vector> //Variable size array.
#include <algorithm> //We use sorting from it.
using namespace std;
int main()
{
int y = 0;
int turnCount = 0;
int count1 = 0, count0 = 0;
bitset <4> inpSeq;
int polyLoc;
bitset <4> operSeq;
bitset <4> bit;
vector <int> xorArray;
vector <int> keyReg;
cout << "Enter a 4-bit sequence: \n";
cin >> inpSeq;
cout << "Enter polynomial:";
cin >> polyLoc;
while(polyLoc>0)
{
xorArray.push_back(polyLoc%10);
polyLoc/=10;
}
cout << "xorArray is: ";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << " ";
}
sort(xorArray.rbegin(), xorArray.rend());
cout << "\n";
operSeq = inpSeq;
keyReg.push_back(inpSeq[0]);
int x = xorArray[0];
cout << "x is: " << x << "\n";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << "\n";
}
cout << "bit 3 of initial " << bit[3] << "\n";
do {
for (unsigned int r = 1; r < xorArray.size(); r++)
{
bit[3] = operSeq[x];
cout << "bit 3 from prev: " << bit[3] << "\n";
y = xorArray[r];
cout << "opseq[y] is: " << operSeq[y] << "\n";
bit[3] = bit[3] ^ operSeq[y];
cout << "bit[3] after xor: " << bit[3] << "\n";
}
operSeq >>= 1;
cout <<"operSeq after shift: " << operSeq << "\n";
operSeq[3] = bit[3];
cout <<"opserSeq bit 4 after = bit[3]: " << operSeq[3] << "\n";
cout <<"new operSeq: " << operSeq << "\n";
keyReg.push_back(operSeq[0]);
turnCount ++;
cout << "--\n";
}
while ((operSeq != inpSeq) && (turnCount < 20));
cout << "Generated key is: ";
for (unsigned int k = 0; k < keyReg.size(); k++)
{
cout << keyReg[k];
}
cout << "\n";
cout << "Bit 1 positions: ";
for ( unsigned int g = 0; g < xorArray.size(); g++)
{
cout << xorArray[g];
}
cout << "\n";
cout << "Key length is: " << keyReg.size();
cout << "\n";
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
count1++;
}
else {
count0++;
}
}
cout << "Number of 0's: " << count0 << "\n";
cout << "Number of 1's: " << count1 << "\n";
if ( keyReg.size()%2 ==0)
{
cout << "key length is even. \n";
if (count1==count0)
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
else
{
cout << "key length is odd. \n";
if ((count1==count0+1) || (count0==count1+1))
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
cin.get();
}

std::vector has an optimization for std::vector<bool>, and the size of a vector can be set at runtime.

Related

error: request for member ‘find’ in ‘sentence’, which is of non-class type ‘char*’ [duplicate]

This question already has answers here:
What is array to pointer decay?
(11 answers)
Array Size Member Function Compile Error
(3 answers)
Closed 15 days ago.
I get an error saying "'find' in ‘sentence’, which is of non-class type ‘char*’".
So the instruction was to enter a string and identify which in the string is a noun, pronoun, adjectives and a linking verb. Everything seems to work except the ".find" part. I really need help.
(btw, nvm the other unecessary things. I made the code shorter to put focus more on the problem)
#include <iostream>
#include <cstring>
#include <cctype>
#include <string>
using namespace std;
string student_id, first_name, last_name, middle_name, suffix;
char sentence[100][100];
char history1[100][100];
int h = 0, s= 0;
char noun[20][20] = {"Ervin", "Rafi", "Peco", "luis", "Edgar", "Benj", "Rias", "Aki", "Naruto", "Jhay", "Josh", "Jopay", "Sasuke", "Joshua", "Trump", "Benjo", "Alice", "Janelle", "Samantha", "Jairah"};
char pronoun[20][20] = {"he", "she", "i", "it", "you"};
char verb[20][20] = {"is", "was", "are", "as", "am"};
char adj[20][20] = {"big", "small", "racist", "fat", "Funny", "gay", "black", "white", "rainbow", "tiny", "smart", "bi", "pan", "stupid", "idiot", "buang", "retard", "gaymer", "special", "talented"};
void display_dictionary();
void open_checker();
bool hasElement(char sentence[], char elements[], int size);
int main()
{
int option;
cout << endl << "Account Menu" <<endl;
cout << "[1] Open checker" << endl;
cout << "[2] Display Dictionary" << endl;
cout << "Option: ";
cin >> option;
switch (option){
case 1: open_checker(); break;
case 2: display_dictionary(); break;
}
return 0;
}
void display_dictionary(){
cout << "List of Nouns: ( ";
for (int n = 0; n < 20; n++){
cout << noun[n] << " " ;
}
cout << ")" << endl << endl;
cout << "List of Pronouns: ( ";
for (int n = 0; n < 5; n++){
cout << pronoun[n] << " " ;
}
cout << ")" << endl << endl;
cout << "List of Linking Verbs: ( ";
for (int n = 0; n < 5; n++){
cout << verb[n] << " " ;
}
cout << ")" << endl << endl;
cout << "List of Adjectives: ( ";
for (int n = 0; n < 20; n++){
cout << adj[n] << " " ;
}
cout << ")" << endl << endl;
}
void open_checker(){
int option;
cout << "Enter Sentence: ";
cin.ignore();
cin.get(sentence[s], 100);
if (hasElement(sentence[s], noun[s], 20)){
cout << " Is a noun." << endl;
}
if (hasElement(sentence[s], adj[s], 20)){
cout << " Is an Adjectives." << endl;
}
if (hasElement(sentence[s], verb[s], 5)){
cout << " Is a Linking Verb." << endl;
}
if (hasElement(sentence[s], pronoun[s], 5)) {
cout << " Is a Linking Verb." << endl;
}
else {
cout << "Sentence does not have all required elements." << endl;
}
strcpy(history1[h], sentence[s]);
history1[h][h] = sentence[s][s];
h++;
s++;
cout << "Type 1 to go back: ";
cin >> option;
if (option == 1){
main();
}
}
bool hasElement(char sentence[], char elements[], int size){
for (int i = 0; i < size; i++) {
if (sentence.find(elements[i]) != string::npos) {
cout << elements[i];
return true;
}
}
return false;
}```

Unhandled exception at 0x012B1CA9

I am new to C++ and am trying to build a simple program that with the users input to proceed will generate a random left or right. I had the program working correctly until I added in the array to try and store each item as I have to output them as soon and the user would like to exit the loop. The program seems to compile fine but at run time I receive "Unhandled exception at 0x012B1CA9" Any help would be greatly appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = '100';
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
for (int i = 1; i < MAX; i++)
{
srand(time(NULL));
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
You have a multi-character constant here... and the behavior doesn't go as expected...
Change this line
const int MAX = '100';
to
const int MAX = 100;
Note the removed single quotes.
And secondly, I will advice you to remove the Seed of the C random generator from the for loop because, you'll likely get the same values from the rand() if you always call it immediately after seeding...
But preferable use the algorithm from C++'s random header
Here is a corrected version of your original code....
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = 100; // <---changed
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
srand(time(NULL)); //< moved to here
for (int i = 0; i < MAX; i++) // <-- modified starting index
{
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
I think that it is basically good idea to read more about C data types and declaration. Your error:
const int MAX = '100' should be const int MAX = 100 without any quotes. C++ does implicit conversion from character literals to int.

Why does my code perform the later cout first?

The following code
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
bool checkPerm(unsigned long long x){
vector<unsigned long long> tester;
string strx = to_string(x);
int sizestrx = strx.size();
int counter = 1;
cout << "x is " << strx << " and its permutations are ";
while (next_permutation(strx.begin(), strx.end())){
cout << strx << " ";
unsigned long long stoipermstrx = stoi(strx);
tester.push_back(stoipermstrx);
}
cout << endl;
int sizetester = tester.size();
for (int j = 2; j <= 6; j++){
cout << "j is " << j << ' ';
for (int k = 0; k < sizetester; k++){
if (j*x == tester[k]){
cout << "counter increased because x, counter " << x << " " << counter << endl;
counter++;
if (counter == 6){
cout << "Number is " << x << endl;
return true;
}
break;
}
}
//cout << "Number " << x << " failed" << endl;
return false;
}
return true;
}
int main(){
unsigned long long x = 1;
for (double i = 0; ; i++){
cout << i << endl;
while (x < 1.67*pow(10, i)){
if (i == 5)
cout << x << endl;
if (checkPerm(x)){
cin.get();
}
x++;
}
x = pow(10, (i + 1));
}
cin.get();
}
has the following problems in this piece of code:
cout << "x is " << strx << " and its permutations are ";
while (next_permutation(strx.begin(), strx.end())){
cout << strx << " ";
unsigned long long stoipermstrx = stoi(strx);
tester.push_back(stoipermstrx);
}
cout << endl;
int sizetester = tester.size();
for (int j = 2; j <= 6; j++){
cout << "j is " << j << ' ';
for (int k = 0; k < sizetester; k++){
if (j*x == tester[k]){
cout << "counter increased because x, counter " << x << " " << counter << endl;
counter++;
if (counter == 6){
cout << "Number is " << x << endl;
return true;
}
break;
}
}
//cout << "Number " << x << " failed" << endl;
return false;
}
Here the output will be "j is j x is x and its permutations are (permutations of x)". HOWEVER, the console should print "x is x and its permutations are (permutations) j is j". The following sample output is given:
j is 2 x is 1355 and its permutations are 1535 1553 3155 3515 3551 5135 5153 531
5 5351 5513 5531
j is 2 x is 1356 and its permutations are 1365 1536 1563 1635 1653 3156 3165 351
6 3561 3615 3651 5136 5163 5316 5361 5613
It appears there are two (minor) things about this. One, you are not looking at the value of sizetester before printing the value of j, and you are not printing a newline after the value of j. This means you are displaying the value of j for the previous loop at the beginning of your line for the current 'x'. If I understand what your code is supposed to be doing, it seems to be doing it correctly -- it's just the way that the output is getting displayed that makes it confusing.
Try this:
int sizetester = tester.size();
for (int j = 2; j <= 6; j++){
if (sizetester){ // <-- added test (see below)
cout << "j is " << j << '\n'; // <-- added newline
} // <--
The test against sizetester suppresses spurious printings of values for j - you later test that (k < sizetester) anyway. The newline just prevents values of j from starting the line for the next values of x, which appears to be the cause of the confusing output.

"Run-Time Check Error #2 - Stack around the variable "arr" was corrupted" when I use a file with many numbers

This is supposed to read at most 1000 numbers from a file into an array and then analyze them. It works flawlessly unless I use a file with a million numbers in it. I probably because I have an infinite loop, but I can't find where. I'm not supposed to go over 1000 elements.
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
const long N=1000;
using namespace std;
//declaring the functions
int readArray(ifstream& ifile, long arr[]);
void sortArray(long arr[], int numberInTheArray);
int main()
{
//variable declaration
int n=0;
int i=0;
int numberInTheArray=0;
long minimum=0;
long maximum=0;
long arr[N]={0};
ifstream ifile;
string strVar;
cout << "Input File Name: ";
cin >> strVar;
cout << "Which number do you want to return? ";
cin >> i;
cout << endl;
ifile.open(strVar.c_str());
if(!ifile)
{
cout << "That file does not exist!" << endl;
return 1;
}
numberInTheArray = readArray(ifile,arr);
if (numberInTheArray == 0){
cout << "The file is empty!" << endl;
}
else{
maximum = arr[n];
minimum = arr[n];
n++;
while (n<=N){
if (arr[n] <= minimum){
minimum = arr[n];
}
if (arr [n] >= maximum){
maximum = arr[n];
}
n++;
}
cout << "Before Sort:\n" << " Min is {" << minimum << "}.\n" << " Max is {"
<< maximum << "}.\n";
if (i>N){
cout << " " << i << " is bigger than 1000!" << endl;
}
else if (numberInTheArray < N){
cout << " WARNING: Only " << numberInTheArray
<< " numbers were read into the array!" << endl;
if (i <= numberInTheArray){
cout << " Value " << i << " is {" << arr[i-1] << "}." << endl;
}
else {
cout << " There aren't that many numbers in the array!" << endl;
}
}
else {
cout << " Value " << i << " is {" << arr[i-1] << "}." << endl;
}
sortArray(arr,numberInTheArray);
cout << "\nAfter Sort:\n" << " Min is {" << minimum << "}.\n" << " Max is {"
<< maximum << "}.\n";
if (i>N){
cout << " " << i << " is bigger than 1000!" << endl;
}
else if (numberInTheArray < N){
cout << " WARNING: Only " << numberInTheArray
<< " numbers were read into the array!" << endl;
if (i <= numberInTheArray){
cout << " Value " << i << " is {" << arr[i-1] << "}." << endl;
}
else {
cout << " There aren't that many numbers in the array!" << endl;
}
}
else {
cout << " Value " << i << " is {" << arr[i-1] << "}." << endl;
}
}
return 0;
}
int readArray(ifstream& ifile, long arr[])
{
int n=0;
long num;
while (n<=N && ifile){
ifile >> arr[n];
n++;
}
n=n-1;
return n;
}
void sortArray(long arr[], int numberInTheArray)
{
int a;
int b;
int temp;
for (a=0; a<numberInTheArray; a++)
{
for (b=0; b<numberInTheArray; b++)
{
if (arr[a] < arr[b])
{
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
}
}
The problem is your loop conditions n <= N. Remember that array indexes goes from zero to size minus one, so the condition should be n < N.

Resizing a dynamic bitset in C++ to a length entered by the user

This C++ program asks the user to enter the length of the bit sequence he/she will enter next. This length variable is named xx, it is of type int. I am using three dynamic bitset with the initial size of 5, these are inpSeq, operSeq and bit. I am resizing the bitsets by
inpSeq.resize(xx); for example. When compiling the program, a very big list of errors appears, I feel I can't paste it here. but I am sure that these errors are all related to this variable xx, the code was compiled fine before using it as a variable to resize the bitset. What is wrong with the way I am resizing the bitset? And can I make the bitsets of the size of inpSeq without asking the user to enter the length of inpSeq bitset?
#include <iostream> //Standard library.
#include <boost/dynamic_bitset.hpp> //Library for 10 handling.
#include <vector> //Variable size array.
#include <algorithm> //We use sorting from it.
using namespace std;
int main()
{
int y = 0;
int turnCount = 0;
int count1 = 0, count0 = 0;
int xx = 0;
boost::dynamic_bitset<> inpSeq(5);
int polyLoc;
boost::dynamic_bitset<> operSeq(5);
boost::dynamic_bitset<> bit(5);
vector <int> xorArray;
vector <int> keyReg;
cout << "What is the legnth of the sequence?";
cin << xx;
inpSeq.resize(xx);
operSeq.resize(xx);
bit.resize(xx);
cout << "Enter a bit sequence: \n";
cin >> inpSeq;
int seq_end = inpSeq.size() - 1;
cout << "Enter polynomial:";
cin >> polyLoc;
while(polyLoc>0)
{
xorArray.push_back(polyLoc%10);
polyLoc/=10;
}
cout << "xorArray is: ";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << " ";
}
sort(xorArray.rbegin(), xorArray.rend());
cout << "\n";
operSeq = inpSeq;
keyReg.push_back(inpSeq[0]);
int x = xorArray[0];
cout << "x is: " << x << "\n";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << "\n";
}
cout << "bit 3 of initial " << bit[seq_end] << "\n";
do {
for (unsigned int r = 1; r < xorArray.size(); r++)
{
bit[seq_end] = operSeq[x];
y = xorArray[r];
bit[seq_end] = bit[seq_end] ^ operSeq[y];
}
operSeq >>= 1;
operSeq[seq_end] = bit[seq_end];
keyReg.push_back(operSeq[0]);
turnCount ++;
cout << "--\n";
}
while ((operSeq != inpSeq) && (turnCount < 20));
cout << "Generated key is: ";
for (unsigned int k = 0; k < keyReg.size(); k++)
{
cout << keyReg[k];
}
cout << "\n";
cout << "Bit 1 positions: ";
for ( unsigned int g = 0; g < xorArray.size(); g++)
{
cout << xorArray[g];
}
cout << "\n";
cout << "Key length is: " << keyReg.size();
cout << "\n";
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
count1++;
}
else {
count0++;
}
}
cout << "Number of 0's: " << count0 << "\n";
cout << "Number of 1's: " << count1 << "\n";
if ( keyReg.size()%2 ==0)
{
cout << "key length is even. \n";
if (count1==count0)
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
else
{
cout << "key length is odd. \n";
if ((count1==count0+1) || (count0==count1+1))
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
cin.get();
}