How can I properly read the input from the console? - c++

I expected that std::cin >> command; would get one command (push, front, pop)
and if (command == "push") to get the value in the variable val with std::cin >> val;
What actually happens is that command gets both commands and values, and val gets nothing.
Input:
12
push 5
push 4
front
push 7
push -5
pop
front
pop
front
push 11
front
pop
#include <bits/stdc++.h>
int queue[1000], size;
void pop();
void push_back(int val);
int main()
{
int n;
std::cin >> n;
char command[10];
int val;
for(int i = 0; i < n; ++i)
{
std::cin >> command;
//std::cout << command << '\n';
if (command == "pop")
pop();
else if (command == "push")
{
std::cin >> val;
//std::cout << val << '\n';
push_back(val);
}
else if (command == "front" && size)
std::cout << queue[0] << '\n';
}
}
void pop()
{
if (size)
{
for(int i = 0; i < size - 1; ++i)
queue[i] = queue[i + 1];
--size;
}
}
void push_back(int val)
{
if (size < sizeof(queue) / sizeof(int))
queue[size++] = val;
}

Related

issue with pointers and count

I need to build a code where it takes a 2d array of char and checks if its palindrome the second function uses the first one to see how many arrays are palindrome my issue with the code is that every time I get count is 0; I know the issue is in the second function but don't know where
#include <iostream>
using namespace std;
int CountPal(char M[][5], int rows);
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
}
int main() {
int x;
cout << "please enter the number of rows " << endl;
cin >> x;
char M[5][5];
cout << "before test" << endl;
cout << CountPal(M, x) << endl;
cout << "After test" << endl;
system("pause");
}
int CountPal(char M[][5], int rows) {
int count = 0;
cout << "please enter the string " << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < 5; j++) {
cin >> M[i][j];
}
for(int i = 0; i < rows; i++) {
char* S;
S = &M[i][0];
if(pal(S) == 1) count++;
}
}
return count;
}
I think your problem is in int pal(char* S) function. You want it to return 1 if a given string of your 2d array is a palindrome to up your count by 1. And anything other than 1 would be non palindrome string.
So i think you should add a return statement after the end of your int pal(char* S) function like this;
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
return flag;
}
You could even change your function to bool data type. It's more proper because you only want to return "true" or "false" values.

Why am I not able to push a pair after a limit in the vector?

The problem is to find if a given sequence of numbers can form a valid permutation or not. The problem statement is trivial for the real problem. So, I am pushing a pair of integers into the vector. The first part being the number itself and second being 0 or 1.
The code works fine till a sequence 1041 long (specific after debugging a lot). Just to debug I added a print statement after pushing each pair inside the vector. For a length of 1042, the code shows pushed 1040 and then pushed 1 (which is weird) and then just hangs on there.
I am attaching the code as well as the input and terminal output.
You can just check the main function
Code
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
using namespace std;
bool comparator_function(pair<int, int> a, pair<int, int> b) {
return (a.first < b.first);
}
//index_added -> the index at which the latest element was added
void set_r_array(int* r_array_ref, int* per_array_ref, int size, int* count, int index_added) {
for(int i = 1;i <= size; i++) {
count[i] = 0;
}
int temp = index_added;
while(index_added <= size) {
if(index_added == size) {
if(per_array_ref[index_added] == 0) {
r_array_ref[temp] = size;
break;
}
else {
r_array_ref[temp] = -1;
break;
}
}
else {
if(per_array_ref[index_added] == 0) {
r_array_ref[temp] = index_added;
break;
}
else {
index_added++;
}
}
}
for(int i = 1;i <= size; i++) {
if(r_array_ref[i] != -1) {
count[r_array_ref[i]]++;
}
}
}
bool check_max(int* count, int next_element, int size) {
int max_count = -1, index = 0;
for(int i = 1;i <= size; i++) {
int temp_val = count[i];
if(max_count <= temp_val) {
max_count = temp_val;
index = i;
}
}
int num = 0;
for(int i = 1;i <= size; i++) {
if(count[i] == max_count) {
num++;
}
}
//one max
if(num == 1) {
if(next_element == index) {
return true;
}
return false;
}
else {
for(int i = 1;i <= size; i++) {
if(count[i] == max_count) {
if(next_element == i) {
return true;
}
}
}
return false;
}
}
int main() {
int testCases;
cin >> testCases;
cin.ignore();
while(testCases-- > 0) {
int n, result_flag = 0;
cin >> n;
cin.ignore();
vector<pair<int, int>> per;
int temp;
for(int i = 0;i < n; i++) {
cin >> temp;
pair<int, int> temp_pair = make_pair(temp, i+1);
per.push_back(temp_pair);
//debug statement
cout << "pushed " << temp << endl;
}
auto start = std::chrono::high_resolution_clock::now();
cout << "start" << endl;
sort(per.begin(), per.end(), comparator_function);
int permutation_array[n+1], r_array[n+1], count[n+1];
for(int i = 0;i <= n; i++) {
permutation_array[i] = 0;
r_array[i] = i;
count[i] = 1;
}
cout << "end" << endl;
permutation_array[per[0].second] = per[0].first;
set_r_array(r_array, permutation_array, n, count, per[0].second);
//insertion of numbers
for(int i = 1;i < n; i++) {
//check if the next element inserted has the largest count rn or not
int next_element = per[i].second;
if(!check_max(count, next_element, n)) {
cout << "No" << endl;
result_flag = -1;
break;
}
permutation_array[per[i].second] = per[i].first;
set_r_array(r_array, permutation_array, n, count, per[i].second);
}
if(result_flag == 0) {
cout << "Yes" << endl;
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
cout << "Time: " << duration.count() << " microseconds" << endl;
}
}
Input 1
1
5
2 3 4 5 1
Output 1
pushed 2
pushed 3
pushed 4
pushed 5
pushed 1
start
end
Yes
Input 2
1
1042
1 2 3 4 ... so on till 1042
Output 2
pushed 1
pushed 2
.
.
.
pushed 1040
pushed 1
and then hangs, from here on
The complexity of the code is O(n^2). So, I don't think it has to do anything with that. Since the input can be at max 10^4 order. Moreover, according to the print debugging, I think the issue is with the input.
You have issue with input as you reach console line limit.
Put your input into a file should solve that issue.
Then you should be able to debug your algorithm which seems more complicated than needed.

Bubble Sort not working correctly

I've been working on this for awhile and I have tried multiple different algorithms for the bubble sort that I have found online but none of them are working properly for me and I'm pretty close to giving up, but this is due tomorrow night. I'd really appreciate if someone could point out where im going wrong. I dont really understand this algorithm with the bool so ill try to find what i was trying before and edit it in
#include <iostream>
using namespace std;
void GetInfo(int[], int&);
void BubbleSort(int[], int);
void BinarySearch(int[], int);
int main()
{
int size;
int array[500];
GetInfo(array, size);
BubbleSort(array, size);
BinarySearch(array, size);
return 0;
}
void GetInfo(int array[], int& size)
{
cout << "Enter the number of naturals: ";
cin >> size;
cout << "Enter the natural numbers to sort: ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
}
void BubbleSort(int array[], int size)
{
int temp;
bool check = true;
int end = 0;
while(check)
{
end++;
check = false;
for(int i = 0; i < size - end; i++)
{
if (array[i] > array[i+1]) //I'm positive this part is correct
{
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
check = true;
}
}
}
cout << endl << "Numbers sorted in ascending order: " << endl;
for (int i = 0; i < size; i++)
{
cout << array[i] << ' ';
}
}
void BinarySearch(int array[], int size) //this doesnt work properly atm but
{ //should be good when the sort works
int index;
int top = size - 1;
int bottom = 0;
int middle = (top) / 2;
bool found = false;
int target;
cout << endl << "Enter the number to search: ";
cin >> target;
while (found == false)
{
if (target > array[middle])
{
bottom = middle + 1 ;
middle = ((top - bottom)/2) + bottom;
}
else if (target < array[middle])
{
top = middle - 1;
middle = ((top - bottom)/2) + bottom;
}
else
{
found = true;
index = middle;
}
}
cout << "Number " << target << " is found in position " << index << endl;
}
You might meant to swap a[i] with a[i+1] while you actually swapped a[size+1]
These lines are wrong:
array[i] = array[size+1];
array[size+1] = temp;
You need:
array[i] = array[i+1];
array[i+1] = temp;

File reading trouble

#Jason Ball this is the whole function:
std::ifstream InFile(filename);
if (!InFile)
return E_FAIL;
std::vector<Layer>Layers;
std::vector<PatternSet>Patterns;
std::vector<Mood>Moods;
Layer layer;
PatternSet ps;
Mood mood;
Theme theme;
layer.fileInfo.padding = layer.fileInfo.data = nullptr;
layer.fileInfo.len = 0;
std::string cmd;
while (true)
{
InFile >> cmd;
if (!InFile)
break;
if (cmd == "f")
{
InFile >> layer.fileInfo.filename;
}
else if (cmd == "fp")
{
int data, n; InFile >> n;
for (int a = 0; a < n; a++)
{
InFile >> data;
layer.fadePoints.push_back(data);
}
}
else if (cmd == "sp")
{
int data, n; InFile >> n;
for (int a = 0; a < n; a++)
{
InFile >> data;
layer.syncPoints.push_back(data);
}
}
else if (cmd == "v")
{
InFile >> layer.volume;
}
else if (cmd == "#layerend")
{
Layers.push_back(layer);
}
else if (cmd == "#patternset")
{
int Index;
for (int a = 0; a < 5; a++)
{
InFile >> Index;
if (Index != -1)
ps.pattern[a] = std::move(Layers[Index]);
}
Patterns.push_back(ps);
memset(ps.pattern, 0, sizeof(Layer)* 5);
}
else if (cmd == "#mood")
{
InFile >> mood.name;
int Index, n; InFile >> n;
for (int a = 0; a < n; a++)
{
InFile >> Index;
mood.data.push_back(Patterns[Index]);
}
Moods.push_back(mood);
mood.data.clear();
}
else if (cmd == "#theme")
{
InFile >> theme.name;
int Index, n; InFile >> n;
for (int a = 0; a < n; a++)
{
InFile >> Index;
theme.data.push_back(Moods[Index]);
}
m_vTheme.push_back(theme);
theme.data.clear();
}
else
{
}
}
return S_OK;
and here is a file:
#layer
f filename
fp 4 0 1998 1245 1003482
sp 3 500 1200 9500
v 0.95
#layerend
#layer
f filename2
fp 4 0 1998 1245 1003482
sp 3 500 1200 9500
v 0.75
#layerend
#patternset -1 0 -1 -1 -1
#patternset -1 1 -1 -1 -1
#mood name n 0 1
#theme name n 0
#Jason Ball here you have those structures as well:
struct node
{
union{
struct{
std::string filename;
void *padding;
};
struct{
void *data;
unsigned int len;
};
};
};
struct Theme;
struct Mood;
struct PatternSet;
struct Layer
{
node fileInfo;
std::vector<int> fadePoints;
std::vector<int> syncPoints;
float volume;
PatternSet *pUp;
};
struct PatternSet
{
union{
struct{
Layer pattern[5];
};
struct{
Layer start;
Layer main;
Layer end;
Layer rhytmic;
Layer incidental;
};
};
Mood *pUp;
};
struct Mood
{
std::vector<PatternSet> data;
std::string name;
Theme *pUp;
};
struct Theme
{
std::vector<Mood> data;
std::string name;
};
When I set breakpoints everywhere, it shows that after first if block it jumps to return line even when the file contains more than 5 000 lines.
I had the same problem a few months ago, but it somehow got to work. Any ideas what can cause this problem?
try this. Hope it helps.
{
ifstream InFile("text.txt");
if (!InFile) return 0;
string cmd;
while (InFile >> cmd)
{
cout << "\ncmd " << cmd;
if (cmd == "f")
{
string name;
if (InFile >> name) {
layer.fileInfo.filename = name;
cout << "\nfilename: " << layer.fileInfo.filename;
}
}
else if (cmd == "fp")
{
int data, n;
if (InFile >> n) {
for (int a = 0; a < n; a++)
{
if (InFile >> data) {
cout << "\nAdding " << data;
layer.fadePoints.push_back(data);
}
}
}
}
else if (cmd == "sp")
{
int data, n;
if (InFile >> n) {
for (int a = 0; a < n; a++)
{
if (InFile >> data) {
layer.syncPoints.push_back(data);
}
}
}
}
else if (cmd == "v")
{
float vol;
if (InFile >> vol) {
layer.volume = vol;
}
}
else if (cmd == "#layerend")
{
Layers.push_back(layer);
}
else if (cmd == "#patternset")
{
int Index;
for (int a = 0; a < 5; a++)
{
if (InFile >> Index) {
if (Index != -1) {
ps.pattern[a] = std::move(Layers[Index]);
}
}
}
Patterns.push_back(ps);
memset(ps.pattern, 0, sizeof(Layer)* 5);
}
else if (cmd == "#mood")
{
if (InFile >> mood.name) {
cout << "\nmood.name " << mood.name;
int Index, n;
if (InFile >> n) {
for (int a = 0; a < n; a++)
{
if (InFile >> Index) {
cout << "\nmood.data.push_back( " << Index << " )";
mood.data.push_back(Patterns[Index]);
}
}
Moods.push_back(mood);
}
}
}
else if (cmd == "#theme")
{
if (InFile >> theme.name) {
cout << "\ntheme.name " << theme.name;
int Index, n;
if (InFile >> n) {
for (int a = 0; a < n; a++)
{
if (InFile >> Index) {
cout << "\ntheme.data.push_back( " << Index << " )";
theme.data.push_back(Moods[Index]);
}
}
m_vTheme.push_back(theme);
}
}
}
else
{
//
}
}
return 1;
}

Implementing a Selection Sort on an Array Based List

My question is what am I doing wrong. The insert function doesn't work correctly. I am unable to retrieve the list itself. And because of this my selection sort won't execute. Any help would be appreciated.
Header:
/** #file ListA.h */
#include <string>
using namespace std;
const int MAX_LIST = 100;
typedef string ListItemType;
class List
{
public:
List();
bool isEmpty() const;
int getLength() const;
void insert(int index, const ListItemType& newItem, bool& success);
void retrieve(int index, ListItemType& dataItem, bool & success) const;
void remove(int index, bool& success);
int selectionSortArray(int numdata[], int xnums);
List selectionSort(List selectList);
private:
ListItemType items[100];
int size;
int translate(int index) const;
};
CPP:
/** #file ListA.cpp */
#include "ArrayList.h" // header file
#include <iostream>
#include <fstream>
List::List() : size()
{
}
bool List::isEmpty() const
{
return size == 0;
}
int List::getLength() const
{
return size;
}
void List::insert(int index, const ListItemType& newItem, bool& success)
{
success = (index >= 1) &&
(index <= size + 1) &&
(size < MAX_LIST);
if (success)
{
for (int pos = size; pos >= index; --pos)
items[translate(pos + 1)] = items[translate(pos)];
items[translate(index)] = newItem;
++size;
}
}
void List::remove(int index, bool& success)
{
success = (index >= 1) && (index <= size);
if (success)
{
for (int fromPosition = index + 1;
fromPosition <= size;
++fromPosition)
items[translate(fromPosition - 1)] = items[translate(fromPosition)];
--size; // decrease the size of the list by one
} // end if
} // end remove
void List::retrieve(int index, ListItemType& dataItem,
bool& success) const
{
success = (index >= 1) && (index <= size);
if (success)
dataItem = items[translate(index)];
}
int List::translate(int index) const
{
return index - 1;
}
//List List::selectionSort(List selectList)
//{
//return selectList;
int List::selectionSortArray(int numdata[], int xnums)
{
int tmp;
for (int i = 0; i < xnums -1; i++)
for (int j = i+1; j < xnums; j++)
if (numdata[i] > numdata[j])
{
tmp = numdata[i];
numdata[i] = numdata[j];
numdata[j] = tmp;
}
//for( int i = 0; i < 5; i++)
//cout << numdata[i] << " ";
return *numdata;
}
int main()
{
ListItemType insertType = "listItem1";
ListItemType retrieveType = "listitem2";
int numberofitems;
cout << "Please enter the number of data items:" << endl;
cin >> numberofitems;
cout << endl;
cout << "Please enter the data items, one per line:" << endl;
int listofitems[numberofitems];
List myArrayList;
cout << myArrayList.getLength() << endl;
if (myArrayList.isEmpty()) // tests before
{
cout << "This list is empty \n" << endl;
}
else
{
cout << "List is not empty! \n"<< endl;
}
bool mainsucc = true;
for (int i = 0; i<numberofitems; i++)
{
cout << "Enter number " << i+1 << " : " << endl;
cin >> listofitems[i];
}
for (int i =0; i <numberofitems; i++){
myArrayList.insert(listofitems[i], insertType, mainsucc);}
cout << "Size of the list is : " << myArrayList.getLength() << endl;
int listRetrieveSize = myArrayList.getLength();
int listRetrieve[listRetrieveSize];
for (int j=0; j<listRetrieveSize; j++)
{
myArrayList.retrieve(listofitems[j], retrieveType, mainsucc);
}
if (myArrayList.isEmpty()) // tests after
{
cout << "This list is empty \n" << endl;
}
else
{
cout << "List is not empty! \n"<< endl;
}
numberofitems= myArrayList.selectionSortArray(listofitems, numberofitems);
for (int i=0;i>numberofitems;i++)
{
cout<<listofitems[i];
}
return 1;
}
Your selection sort is definitely wrong:
int List::selectionSortArray(int numdata[], int xnums)
{
int tmp;
for (int i = 0; i < xnums -1; i++) {
//you should find the smallest integer inside this for loop
for (int j = i+1; j < xnums; j++) {
if (numdata[i] > numdata[j])
{
//why do you swap inside this for loop?
tmp = numdata[i];
numdata[i] = numdata[j];
numdata[j] = tmp;
}
}//missing closing }
//smap numdata[i] with currently smallest int
}//missing closing }
return *numdata;
}
Your insert function deals with strings, but you are doing selection sort on integers.
typedef string ListItemType;
defines string as ListItemType.
I'm pretty sure that what you have implemented is the Bubble sort algorithm, instead of the selection sort algorithm.